I wrote my own export to Excel writer because nothing else quite met my needs. It is fast and allows for substantial formatting of the cells. You can review it at
https://openxmlexporttoexcel.codeplex.com/
I hope it helps.
Try to use Aspose.cells library (not free, but trial is enough to read), it is quite good
Install-package Aspose.cells
There is sample code:
using Aspose.Cells;
using System;
namespace ExcelReader
{
class Program
{
static void Main(string[] args)
{
// Replace path for your file
readXLS(@"C:\MyExcelFile.xls"); // or "*.xlsx"
Console.ReadKey();
}
public static void readXLS(string PathToMyExcel)
{
//Open your template file.
Workbook wb = new Workbook(PathToMyExcel);
//Get the first worksheet.
Worksheet worksheet = wb.Worksheets[0];
//Get cells
Cells cells = worksheet.Cells;
// Get row and column count
int rowCount = cells.MaxDataRow;
int columnCount = cells.MaxDataColumn;
// Current cell value
string strCell = "";
Console.WriteLine(String.Format("rowCount={0}, columnCount={1}", rowCount, columnCount));
for (int row = 0; row <= rowCount; row++) // Numeration starts from 0 to MaxDataRow
{
for (int column = 0; column <= columnCount; column++) // Numeration starts from 0 to MaxDataColumn
{
strCell = "";
strCell = Convert.ToString(cells[row, column].Value);
if (String.IsNullOrEmpty(strCell))
{
continue;
}
else
{
// Do your staff here
Console.WriteLine(strCell);
}
}
}
}
}
}
Goto Nuget Package manager and search for openxml. And install DocumentFormat.OpenXml
There is a way that may be suitable if the items you want to delete are always at the "beginning" of the dict iteration
while mydict:
key, value = next(iter(mydict.items()))
if should_delete(key, value):
del mydict[key]
else:
break
The "beginning" is only guaranteed to be consistent for certain Python versions/implementations. For example from What’s New In Python 3.7
the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.
This way avoids a copy of the dict that a lot of the other answers suggest, at least in Python 3.
With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)
From this:
declare @anID int
exec @anID = dbo.StoredProc_Fetch @ID, @anotherID, @finalID
exec dbo.ADifferentStoredProc @anID (no value here)
To this:
declare @t table(id int)
declare @anID int
insert into @t exec dbo.StoredProc_Fetch @ID, @anotherID, @finalID
set @anID= (select Top 1 * from @t)
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://example.com",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "value1=111&value2=222",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if (!$err)
{
var_dump($response);
}
The expression df1$id %in% idNums1
produces a logical vector. To negate it, you need to negate the whole vector:
!(df1$id %in% idNums1)
i had this error too as Smutje reffered make sure that you have not a value in foreign key column of your base foreign key table that is not in your reference table i.e(every value in your base foreign key table(value of a column that is foreign key) must also be in your reference table column) its good to empty your base foreign key table first then set foreign keys
From the command line you can convert a notebook to python with this command:
jupyter nbconvert --to python nb.ipynb
https://github.com/jupyter/nbconvert
You may have to install the python mistune package:
sudo pip install -U mistune
Instance of a class when compared with == comes to non-equal. The best way is to ass the cmp function to your class which will do the stuff.
If you want to do comparison by the content you can simply use cmp(obj1,obj2)
In your case cmp(doc1,doc2) It will return -1 if the content wise they are same.
First give your input type submit a name, like this name='submitform'
.
and then put this in your php file
if (isset($_POST['submitform']))
{
?>
<script type="text/javascript">
window.location = "http://www.google.com/";
</script>
<?php
}
Don't forget to change the url to yours.
As the docs say, this can be achieved just by using set
instead if push
.
As the docs say, it is not recommended (due to possible overwrite by other user at the "same" time).
But in some cases it's helpful to have control over the feed's content including keys.
As an example of webapp in js, 193 being your id generated elsewhere, simply:
firebase.initializeApp(firebaseConfig);
var data={
"name":"Prague"
};
firebase.database().ref().child('areas').child("193").set(data);
This will overwrite any area labeled 193 or create one if it's not existing yet.
First, there is a difference between spec and reality. The spec says that System.gc() is a hint that GC should run and the VM is free to ignore it. The reality is, the VM will never ignore a call to System.gc().
Calling GC comes with a non-trivial overhead to the call and if you do this at some random point in time it's likely you'll see no reward for your efforts. On the other hand, a naturally triggered collection is very likely to recoup the costs of the call. If you have information that indicates that a GC should be run than you can make the call to System.gc() and you should see benefits. However, it's my experience that this happens only in a few edge cases as it's very unlikely that you'll have enough information to understand if and when System.gc() should be called.
One example listed here, hitting the garbage can in your IDE. If you're off to a meeting why not hit it. The overhead isn't going to affect you and heap might be cleaned up for when you get back. Do this in a production system and frequent calls to collect will bring it to a grinding halt! Even occasional calls such as those made by RMI can be disruptive to performance.
You can do that using javascript and AJAX technology. Have a look at jquery and at this form plug in. You only need to include two js files to register a callback for the form.submit.
If you are using Jersey (which I was, my server component needs to make outbound HTTP requests) it contains the following public method:
var multiValueMap = UriComponent.decodeQuery(uri, true);
It is part of org.glassfish.jersey.uri.UriComponent
, and the javadoc is here. Whilst you may not want all of Jersey, it is part of the Jersey common package which isn't too bad on dependencies...
Determine the application pool used by the application and set the property of by setting Enable 32 bit applications to True. This can be done through advance settings of the application pool.
The expression 'AND' and 'OR' and 'NOT'
always evaluates to 'NOT'
, so you are effectively doing
while 'NOT' not in some_list:
print 'No boolean operator'
You can either check separately for all of them
while ('AND' not in some_list and
'OR' not in some_list and
'NOT' not in some_list):
# whatever
or use sets
s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
# whatever
public class IntergerParser {
public static void main(String[] args){
String number = "+123123";
System.out.println(parseInt(number));
}
private static int parseInt(String number){
char[] numChar = number.toCharArray();
int intValue = 0;
int decimal = 1;
for(int index = numChar.length ; index > 0 ; index --){
if(index == 1 ){
if(numChar[index - 1] == '-'){
return intValue * -1;
} else if(numChar[index - 1] == '+'){
return intValue;
}
}
intValue = intValue + (((int)numChar[index-1] - 48) * (decimal));
System.out.println((int)numChar[index-1] - 48+ " " + (decimal));
decimal = decimal * 10;
}
return intValue;
}
I am not sure why but the command below worked for me.
pip install pyqt5
Of course I updated Anaconda and Navigator before running this command.
To get sms: and mailto: links to work on both iPhone and Android, without any javascript, try this:
<a href="sms:321-555-1111?&body=This is what I want to sent">click to text</a>
<a href="mailto:[email protected]?&subject=My subject&body=This is what I want to sent">click to email</a>
I tested it on Chrome for Android & iPhone, and Safari on iPhone.
They all worked as expected.
They worked without the phone number or email address as well.
If you have xmllint
you can spawn a subprocess and use it. xmllint --format <file>
pretty-prints its input XML to standard output.
Note that this method uses an program external to python, which makes it sort of a hack.
def pretty_print_xml(xml):
proc = subprocess.Popen(
['xmllint', '--format', '/dev/stdin'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
(output, error_output) = proc.communicate(xml);
return output
print(pretty_print_xml(data))
this worked for me:
ssh-keygen -R <server_IP>
to delete the old keys stored on the workstation also works with instead of
then doing the same ssh again it worked:
ssh -v -i <your_pem_file> ubuntu@<server_IP>
on ubuntu instances the username is: ubuntu on Amazon Linux AMI the username is: ec2-user
I didn't have to re-create the instance from an image.
Another simpler way to do the same thing.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// set this.FormBorderStyle to None here if needed
// if set to none, make sure you have a way to close the form!
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCHITTEST)
m.Result = (IntPtr)(HT_CAPTION);
}
private const int WM_NCHITTEST = 0x84;
private const int HT_CLIENT = 0x1;
private const int HT_CAPTION = 0x2;
}
You can pass multiple arguments like this.
List<object> arguments = new List<object>();
arguments.Add("first"); //argument 1
arguments.Add(new Object()); //argument 2
// ...
arguments.Add(10); //argument n
backgroundWorker.RunWorkerAsync(arguments);
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
List<object> genericlist = e.Argument as List<object>;
//extract your multiple arguments from
//this list and cast them and use them.
}
There are two ways you can do this; with patch and with patch.object
Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following
#foo.py
def some_fn():
return 'some_fn'
class Foo(object):
def method_1(self):
return some_fn()
#bar.py
import foo
class Bar(object):
def method_2(self):
tmp = foo.Foo()
return tmp.method_1()
#test_case_1.py
import bar
from mock import patch
@patch('foo.some_fn')
def test_bar(mock_some_fn):
mock_some_fn.return_value = 'test-val-1'
tmp = bar.Bar()
assert tmp.method_2() == 'test-val-1'
mock_some_fn.return_value = 'test-val-2'
assert tmp.method_2() == 'test-val-2'
If you are directly importing the module to be tested, you can use patch.object as follows:
#test_case_2.py
import foo
from mock import patch
@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
test_some_fn.return_value = 'test-val-1'
tmp = foo.Foo()
assert tmp.method_1() == 'test-val-1'
test_some_fn.return_value = 'test-val-2'
assert tmp.method_1() == 'test-val-2'
In both cases some_fn will be 'un-mocked' after the test function is complete.
Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters
@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
...
Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.
Yes, you can use jQuery's attribute selector for that.
var linksToGoogle = $('a[href="http://google.com"]');
Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:
var allLinksToGoogle = $('a[href^="http://google.com"]');
Try this:
public static boolean isToday(Date date)
{
return org.apache.commons.lang3.time.DateUtils.isSameDay(Calendar.getInstance().getTime(),date);
}
That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.
Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
, Unique:=False
One way to fix an overflow of a Text Widget within a row if for example a chat message can be one really long line. You can create a Container and a BoxConstraint with a maxWidth in it.
Container(
constraints: BoxConstraints(maxWidth: 200),
child: Text(
(chatName == null) ? " ": chatName,
style: TextStyle(
fontWeight: FontWeight.w400,
color: Colors.black87,
fontSize: 17.0),
)
),
Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.
Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.
Calling an external command in Python
Simple, use subprocess.run
, which returns a CompletedProcess
object:
>>> import subprocess
>>> completed_process = subprocess.run('python --version')
Python 3.6.1 :: Anaconda 4.4.0 (64-bit)
>>> completed_process
CompletedProcess(args='python --version', returncode=0)
As of Python 3.5, the documentation recommends subprocess.run:
The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.
Here's an example of the simplest possible usage - and it does exactly as asked:
>>> import subprocess
>>> completed_process = subprocess.run('python --version')
Python 3.6.1 :: Anaconda 4.4.0 (64-bit)
>>> completed_process
CompletedProcess(args='python --version', returncode=0)
run
waits for the command to successfully finish, then returns a CompletedProcess
object. It may instead raise TimeoutExpired
(if you give it a timeout=
argument) or CalledProcessError
(if it fails and you pass check=True
).
As you might infer from the above example, stdout and stderr both get piped to your own stdout and stderr by default.
We can inspect the returned object and see the command that was given and the returncode:
>>> completed_process.args
'python --version'
>>> completed_process.returncode
0
If you want to capture the output, you can pass subprocess.PIPE
to the appropriate stderr
or stdout
:
>>> cp = subprocess.run('python --version',
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
>>> cp.stderr
b'Python 3.6.1 :: Anaconda 4.4.0 (64-bit)\r\n'
>>> cp.stdout
b''
(I find it interesting and slightly counterintuitive that the version info gets put to stderr instead of stdout.)
One might easily move from manually providing a command string (like the question suggests) to providing a string built programmatically. Don't build strings programmatically. This is a potential security issue. It's better to assume you don't trust the input.
>>> import textwrap
>>> args = ['python', textwrap.__file__]
>>> cp = subprocess.run(args, stdout=subprocess.PIPE)
>>> cp.stdout
b'Hello there.\r\n This is indented.\r\n'
Note, only args
should be passed positionally.
Here's the actual signature in the source and as shown by help(run)
:
def run(*popenargs, input=None, timeout=None, check=False, **kwargs):
The popenargs
and kwargs
are given to the Popen
constructor. input
can be a string of bytes (or unicode, if specify encoding or universal_newlines=True
) that will be piped to the subprocess's stdin.
The documentation describes timeout=
and check=True
better than I could:
The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.
If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.
and this example for check=True
is better than one I could come up with:
>>> subprocess.run("exit 1", shell=True, check=True) Traceback (most recent call last): ... subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Here's an expanded signature, as given in the documentation:
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None)
Note that this indicates that only the args list should be passed positionally. So pass the remaining arguments as keyword arguments.
When use Popen
instead? I would struggle to find use-case based on the arguments alone. Direct usage of Popen
would, however, give you access to its methods, including poll
, 'send_signal', 'terminate', and 'wait'.
Here's the Popen
signature as given in the source. I think this is the most precise encapsulation of the information (as opposed to help(Popen)
):
def __init__(self, args, bufsize=-1, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0,
restore_signals=True, start_new_session=False,
pass_fds=(), *, encoding=None, errors=None):
But more informative is the Popen
documentation:
subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, encoding=None, errors=None)
Execute a child program in a new process. On POSIX, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows.
Understanding the remaining documentation on Popen
will be left as an exercise for the reader.
In my case the JWT is created by a separate API so ASP.NET need only decode and validate it. In contrast to the accepted answer we're using RSA which is a non-symmetric algorithm, so the SymmetricSecurityKey
class mentioned above won't work.
Here's the result.
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Threading;
using System.Threading.Tasks;
public static async Task<JwtSecurityToken> VerifyAndDecodeJwt(string accessToken)
{
try
{
var configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{securityApiOrigin}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
var openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);
var validationParameters = new TokenValidationParameters()
{
ValidateLifetime = true,
ValidateAudience = false,
ValidateIssuer = false,
RequireSignedTokens = true,
IssuerSigningKeys = openIdConfig.SigningKeys,
};
new JwtSecurityTokenHandler().ValidateToken(accessToken, validationParameters, out var validToken);
// threw on invalid, so...
return validToken as JwtSecurityToken;
}
catch (Exception ex)
{
logger.Info(ex.Message);
return null;
}
}
If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age)
.
Another way is to use stringstreams:
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
A third approach would be to use sprintf
or snprintf
from the C library.
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
Other posters suggested using itoa
. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.
overflow: hidden; /* Hide scrollbars */
now go to add file .css in project and include file
All the previous posts are correct. There's more than one way to skin a cat. Here is another way to do the same thing: (just replace "what_ever_you_want_to_convert" with your string and run it in Oracle:
set serveroutput on;
DECLARE
v_str VARCHAR2(1000);
BEGIN
--Create encoded value
v_str := utl_encode.text_encode
('what_ever_you_want_to_convert','WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
--Decode the value..
v_str := utl_encode.text_decode
(v_str,'WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
END;
/
Reading through this helps solve a similar problem. The data is in decimal datatype - [DOB] [decimal](8, 0) NOT NULL - eg - 19700109. I want to get at the month. The solution is to combine SUBSTRING with CONVERT to VARCHAR.
SELECT [NUM]
,SUBSTRING(CONVERT(VARCHAR, DOB),5,2) AS mob
FROM [Dbname].[dbo].[Tablename]
The enums should not be qualified within the case label like what you have NDroid.guideView.GUIDE_VIEW_SEVEN_DAY
, instead you should remove the qualification and use GUIDE_VIEW_SEVEN_DAY
ProgressBar:
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="4"
android:indeterminateDrawable="@drawable/progressdrawable"
/>
progressdrawable.xml:
Here use gradient to change colour as you like. And android:toDegrees="X" increse the value of X and progressbar rotate fast. Decrease and it rotate slow.Customize according to your needs.
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="4000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" >
<shape
android:innerRadius="20dp"
android:shape="ring"
android:thickness="4dp"
android:useLevel="false" >
<size
android:height="48dp"
android:width="48dp" />
<gradient
android:centerColor="#80ec7e2a"
android:centerY="0.5"
android:endColor="#ffec7e2a"
android:startColor="#00ec7e2a"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts
subdirectory.
In CSS code:
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font.woff") format('woff');
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-bold.woff") format('woff');
font-weight: bold;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-boldoblique.woff") format('woff');
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-oblique.woff") format('woff');
font-style: italic;
}
After having that definitions, you can just write, for example,
In HTML code:
<div class="mydiv">
<b>this will be written with awesome-font-bold.woff</b>
<br/>
<b><i>this will be written with awesome-font-boldoblique.woff</i></b>
<br/>
<i>this will be written with awesome-font-oblique.woff</i>
<br/>
this will be written with awesome-font.woff
</div>
In CSS code:
.mydiv {
font-family: myfont
}
The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.
Just put a
List<Person>
into the ViewBag and in the View cast it back to List
Since Node.js v0.12 and as of Node.js v4.0.0, there is a stable readline core module. Here's the easiest way to read lines from a file, without any external modules:
const fs = require('fs');
const readline = require('readline');
async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
}
processLineByLine();
Or alternatively:
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('file.in')
});
lineReader.on('line', function (line) {
console.log('Line from file:', line);
});
The last line is read correctly (as of Node v0.12 or later), even if there is no final \n
.
UPDATE: this example has been added to Node's API official documentation.
The (Linux) command-line tool 'file' is available on Windows via GnuWin32:
http://gnuwin32.sourceforge.net/packages/file.htm
If you have git installed, it's located in C:\Program Files\git\usr\bin.
Example:
C:\Users\SH\Downloads\SquareRoot>file * _UpgradeReport_Files; directory Debug; directory duration.h; ASCII C++ program text, with CRLF line terminators ipch; directory main.cpp; ASCII C program text, with CRLF line terminators Precision.txt; ASCII text, with CRLF line terminators Release; directory Speed.txt; ASCII text, with CRLF line terminators SquareRoot.sdf; data SquareRoot.sln; UTF-8 Unicode (with BOM) text, with CRLF line terminators SquareRoot.sln.docstates.suo; PCX ver. 2.5 image data SquareRoot.suo; CDF V2 Document, corrupt: Cannot read summary info SquareRoot.vcproj; XML document text SquareRoot.vcxproj; XML document text SquareRoot.vcxproj.filters; XML document text SquareRoot.vcxproj.user; XML document text squarerootmethods.h; ASCII C program text, with CRLF line terminators UpgradeLog.XML; XML document text C:\Users\SH\Downloads\SquareRoot>file --mime-encoding * _UpgradeReport_Files; binary Debug; binary duration.h; us-ascii ipch; binary main.cpp; us-ascii Precision.txt; us-ascii Release; binary Speed.txt; us-ascii SquareRoot.sdf; binary SquareRoot.sln; utf-8 SquareRoot.sln.docstates.suo; binary SquareRoot.suo; CDF V2 Document, corrupt: Cannot read summary infobinary SquareRoot.vcproj; us-ascii SquareRoot.vcxproj; utf-8 SquareRoot.vcxproj.filters; utf-8 SquareRoot.vcxproj.user; utf-8 squarerootmethods.h; us-ascii UpgradeLog.XML; us-ascii
A shell script to accomplish this:
#!/bin/bash
# Remove whitespace
function remWS {
if [ -z "${1}" ]; then
cat | tr -d '[:space:]'
else
echo "${1}" | tr -d '[:space:]'
fi
}
for pkg in $(adb shell pm list packages -3 | cut -d':' -f2); do
apk_loc="$(adb shell pm path $(remWS $pkg) | cut -d':' -f2 | remWS)"
apk_name="$(adb shell aapt dump badging $apk_loc | pcregrep -o1 $'application-label:\'(.+)\'' | remWS)"
apk_info="$(adb shell aapt dump badging $apk_loc | pcregrep -o1 '\b(package: .+)')"
echo "$apk_name v$(echo $apk_info | pcregrep -io1 -e $'\\bversionName=\'(.+?)\'')"
done
library(tidyverse)
x <- data.frame(Category= c('First', 'First', 'First', 'Second', 'Third', 'Third', 'Second'),
Frequency = c(10, 15, 5, 2, 14, 20, 3))
count(x, Category, wt = Frequency)
Comparable
is usually preferred. But sometimes a class already implements Comparable
, but you want to sort on a different property. Then you're forced to use a Comparator
.
Some classes actually provide Comparators
for common cases; for instance, String
s are by default case-sensitive when sorted, but there is also a static Comparator
called CASE_INSENSITIVE_ORDER
.
This tutorial should help you:
Getting Started with Oracle SQL Developer
See the prerequisites:
Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:
alter user hr identified by hr account unlock;
Download and unzip the sqldev_mngdb.zip file that contains all the files you need to perform this tutorial.
Another version from May 2011: Getting Started with Oracle SQL Developer
For more info check this related question:
How to create a new database after initally installing oracle database 11g Express Edition?
||= is a conditional assignment operator
x ||= y
is equivalent to
x = x || y
or alternatively
if defined?(x) and x
x = x
else
x = y
end
To increase the phpMyAdmin
Session Timeout, open config.inc.php
in the root phpMyAdmin
directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where <your_new_timeout>
is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
Simply define a function and set the value of your Combobox to empty/null or whatever you want. Try the following.
def Reset():
cmb.set("")
here, cmb
is a variable in which you have assigned the Combobox. Now call that function in a button such as,
btn2 = ttk.Button(root, text="Reset",command=Reset)
There is a trick to push postgres to prefer a seqscan adding a OFFSET 0
in the subquery
This is handy for optimizing requests linking big/huge tables when all you need is only the n first/last elements.
Lets say you are looking for first/last 20 elements involving multiple tables having 100k (or more) entries, no point building/linking up all the query over all the data when what you'll be looking for is in the first 100 or 1000 entries. In this scenario for example, it turns out to be over 10x faster to do a sequential scan.
You cannot ... yet. But this is an alternative, think like a docker-composer.yml generator:
https://gist.github.com/Vad1mo/9ab63f28239515d4dafd
Basically a shell script that will replace your variables. Also you can use Grunt task to build your docker compose file at the end of your CI process.
I'd recommend to strip from the second and the following strings the string os.path.sep
, preventing them to be interpreted as absolute paths:
first_path_str = '/home/build/test/sandboxes/'
original_other_path_to_append_ls = [todaystr, '/new_sandbox/']
other_path_to_append_ls = [
i_path.strip(os.path.sep) for i_path in original_other_path_to_append_ls
]
output_path = os.path.join(first_path_str, *other_path_to_append_ls)
As other stated, it is not needed for C, but for C++.
Including the cast may allow a C program or function to compile as C++.
In C it is unnecessary, as void * is automatically and safely promoted to any other pointer type.
But if you cast then, it can hide an error if you forgot to include stdlib.h. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code).
Because stdlib.h contains the prototype for malloc is found. In the absence of a prototype for malloc, the standard requires that the C compiler assumes malloc returns an int. If there is no cast, a warning is issued when this integer is assigned to the pointer; however, with the cast, this warning is not produced, hiding a bug.
This works perfect for Python 3.5
, if the URL contains Query String / Parameter value,
Request URL = https://bah2.com/ws/rest/v1/concept/
Parameter value = 21f6bb43-98a1-419d-8f0c-8133669e40ca
import requests
url = 'https://bahbah2.com/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca'
data = {"name": "Value"}
r = requests.post(url, auth=('username', 'password'), verify=False, json=data)
print(r.status_code)
You could try:
$j('div.contextualError.ckgcellphone').css('display')
PreparedStatements are the way to go in most, but not all cases. Sometimes you will find yourself in a situation where a query, or a part of it, has to be built and stored as a string for later use. Check out the SQL Injection Prevention Cheat Sheet on the OWASP Site for more details and APIs in different programming languages.
$('a[href$="ABC"]:first').attr('title');
This will return the title of the first link that has a URL which ends with "ABC".
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
For Angular 9+ You can add headers and params directly without the key-value notion:
const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params});
If the audio wrapped into the avi is not mp3-format to start with, you may need to specify -acodec mp3
as an additional parameter. Or whatever your mp3 codec is (on Linux systems its probably -acodec libmp3lame
). You may also get the same effect, platform-agnostic, by instead specifying -f mp3
to "force" the format to mp3, although not all versions of ffmpeg still support that switch. Your Mileage May Vary.
A short answer is to add the following options when the JVM is started.
JAVA_OPTS=" $JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8080"
I suggest you to create a scalar user defined function. This is an example (sorry in advance, because the variable names are in spanish):
CREATE FUNCTION [dbo].[Udf_ReplaceChars] (
@cadena VARCHAR(500), -- String to manipulate
@caracteresElim VARCHAR(100), -- String of characters to be replaced
@caracteresReem VARCHAR(100) -- String of characters for replacement
)
RETURNS VARCHAR(500)
AS
BEGIN
DECLARE @cadenaFinal VARCHAR(500), @longCad INT, @pos INT, @caracter CHAR(1), @posCarER INT;
SELECT
@cadenaFinal = '',
@longCad = LEN(@cadena),
@pos = 1;
IF LEN(@caracteresElim)<>LEN(@caracteresReem)
BEGIN
RETURN NULL;
END
WHILE @pos <= @longCad
BEGIN
SELECT
@caracter = SUBSTRING(@cadena,@pos,1),
@pos = @pos + 1,
@posCarER = CHARINDEX(@caracter,@caracteresElim);
IF @posCarER <= 0
BEGIN
SET @cadenaFinal = @cadenaFinal + @caracter;
END
ELSE
BEGIN
SET @cadenaFinal = @cadenaFinal + SUBSTRING(@caracteresReem,@posCarER,1)
END
END
RETURN @cadenaFinal;
END
Here is an example using this function:
SELECT dbo.Udf_ReplaceChars('This is a test.','sat','Z47');
And the result is: 7hiZ iZ 4 7eZ7.
As you can see, each character of the @caracteresElim
parameter is replaced by the character in the same position from the @caracteresReem
parameter.
Pre-crement means increment on the same line. Post-increment means increment after the line executes.
int j=0;
System.out.println(j); //0
System.out.println(j++); //0. post-increment. It means after this line executes j increments.
int k=0;
System.out.println(k); //0
System.out.println(++k); //1. pre increment. It means it increments first and then the line executes
When it comes with OR, AND operators, it becomes more interesting.
int m=0;
if((m == 0 || m++ == 0) && (m++ == 1)) { //false
/* in OR condition if first line is already true then compiler doesn't check the rest. It is technique of compiler optimization */
System.out.println("post-increment "+m);
}
int n=0;
if((n == 0 || n++ == 0) && (++n == 1)) { //true
System.out.println("pre-increment "+n); //1
}
In Array
System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 } ;
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); //12
jj = a[1]++; //12
System.out.println(a[1]); //a[1] = 13
mm = a[1];//13
System.out.printf ( "\n%d %d %d\n", ii, jj, mm ) ; //12, 12, 13
for (int val: a) {
System.out.print(" " +val); //55, 13, 15, 20, 25
}
In C++ post/pre-increment of pointer variable
#include <iostream>
using namespace std;
int main() {
int x=10;
int* p = &x;
std::cout<<"address = "<<p<<"\n"; //prints address of x
std::cout<<"address = "<<p<<"\n"; //prints (address of x) + sizeof(int)
std::cout<<"address = "<<&x<<"\n"; //prints address of x
std::cout<<"address = "<<++&x<<"\n"; //error. reference can't re-assign because it is fixed (immutable)
}
An old thread, but there is another alternative.
Since 9i you can use pipelined table function.
First, create a type as a table of varchar:
CREATE TYPE t_string_max IS TABLE OF VARCHAR2(32767);
Second, wrap your code in a pipelined function declaration:
CREATE FUNCTION fn_foo (bar VARCHAR2) -- your params
RETURN t_string_max PIPELINED IS
-- your vars
BEGIN
-- your code
END;
/
Replace all DBMS_OUTPUT.PUT_LINE
for PIPE ROW
.
Finally, call it like this:
SELECT * FROM TABLE(fn_foo('param'));
Hope it helps.
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
try with removeClass
For instance:
var nameClass=document.getElementsByClassName("clase1");_x000D_
console.log("after", nameClass[0]);_x000D_
$(".clase1").removeClass();_x000D_
var nameClass=document.getElementsByClassName("clase1");_x000D_
console.log("before", nameClass[0]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="clase1">I am Div with class="clase1"</div>
_x000D_
Use the title
attribute while alt
is important for SEO stuff.
Weak references are collected eagerly. If GC finds that an object is weakly reachable (reachable only through weak references), it'll clear the weak references to that object immediately. As such, they're good for keeping a reference to an object for which your program also keeps (strongly referenced) "associated information" somewere, like cached reflection information about a class, or a wrapper for an object, etc. Anything that makes no sense to keep after the object it is associated with is GC-ed. When the weak reference gets cleared, it gets enqueued in a reference queue that your code polls somewhere, and it discards the associated objects as well. That is, you keep extra information about an object, but that information is not needed once the object it refers to goes away. Actually, in certain situations you can even subclass WeakReference and keep the associated extra information about the object in the fields of the WeakReference subclass. Another typical use of WeakReference is in conjunction with Maps for keeping canonical instances.
SoftReferences on the other hand are good for caching external, recreatable resources as the GC typically delays clearing them. It is guaranteed though that all SoftReferences will get cleared before OutOfMemoryError is thrown, so they theoretically can't cause an OOME[*].
Typical use case example is keeping a parsed form of a contents from a file. You'd implement a system where you'd load a file, parse it, and keep a SoftReference to the root object of the parsed representation. Next time you need the file, you'll try to retrieve it through the SoftReference. If you can retrieve it, you spared yourself another load/parse, and if the GC cleared it in the meantime, you reload it. That way, you utilize free memory for performance optimization, but don't risk an OOME.
Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If on the other hand you mistakenly use SoftReference for a task a WeakReference is meant to be used (namely, you keep information associated with an Object somehow strongly referenced, and discard it when the Reference object gets cleared), you can run into OOME as your code that polls the ReferenceQueue and discards the associated objects might happen to not run in a timely fashion.
So, the decision depends on usage - if you're caching information that is expensive to construct, but nonetheless reconstructible from other data, use soft references - if you're keeping a reference to a canonical instance of some data, or you want to have a reference to an object without "owning" it (thus preventing it from being GC'd), use a weak reference.
If the array is unsorted, there isn't really a better way (aside from using the above-mentioned indexOf, which I think amounts to the same thing). If the array is sorted, you can do a binary search, which works like this:
Binary search runs in time proportional to the logarithm of the length of the array, so it can be much faster than looking at each individual element.
you can do this by:
name = 'Bob'
if type(name) == str:
print 'this works'
else:
print 'this does not work'
and it will return 'this works'... but if you change name to int(1) then it will return 'this does not work' because it is now a string... you can also try:
name = int(5)
if type(name) == int:
print 'this works'
else:
print 'this does not work'
and the same thing will happen
I recently created a directive to allow for expression-based invalidation of angular form inputs. Any valid angular expression can be used, and it supports custom validation keys using object notation. Tested with angular v1.3.8
.directive('invalidIf', [function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var argsObject = scope.$eval(attrs.invalidIf);
if (!angular.isObject(argsObject)) {
argsObject = { invalidIf: attrs.invalidIf };
}
for (var validationKey in argsObject) {
scope.$watch(argsObject[validationKey], function (newVal) {
ctrl.$setValidity(validationKey, !newVal);
});
}
}
};
}]);
You can use it like this:
<input ng-model="foo" invalid-if="{fooIsGreaterThanBar: 'foo > bar',
fooEqualsSomeFuncResult: 'foo == someFuncResult()'}/>
Or by just passing in an expression (it will be given the default validationKey of "invalidIf")
<input ng-model="foo" invalid-if="foo > bar"/>
As usual, the best design depends on the particular circumstances. Usually though, I write something like:
for (int retries = 0;; retries++) {
try {
return doSomething();
} catch (SomeException e) {
if (retries < 6) {
continue;
} else {
throw e;
}
}
}
Without any assumptions the answer is:
{% if var is null %}
But this will be true only if var
is exactly NULL
, and not any other value that evaluates to false
(such as zero, empty string and empty array). Besides, it will cause an error if var
is not defined. A safer way would be:
{% if var is not defined or var is null %}
which can be shortened to:
{% if var|default is null %}
If you don't provide an argument to the default
filter, it assumes NULL
(sort of default default). So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc):
{% if var|default is empty %}
When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify()
.
Here is a working example:
var fs = require('fs');
var originalNote = {
title: 'Meeting',
description: 'Meeting John Doe at 10:30 am'
};
var originalNoteString = JSON.stringify(originalNote);
fs.writeFileSync('notes.json', originalNoteString);
var noteString = fs.readFileSync('notes.json');
var note = JSON.parse(noteString);
console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);
Hope it could help.
There's yet another way to do it using Shared Connections, ie: somebody initiates the connection, using a password, and every subsequent connection will multiplex over the same channel, negating the need for re-authentication. ( And its faster too )
# ~/.ssh/config
ControlMaster auto
ControlPath ~/.ssh/pool/%r@%h
then you just have to log in, and as long as you are logged in, the bash script will be able to open ssh connections.
You can then stop your script from working when somebody has not already opened the channel by:
ssh ... -o KbdInteractiveAuthentication=no ....
I would Poly fill the classList functionality and use the new syntax. This way newer browser will use the new implementation (which is much faster) and only old browsers will take the performance hit from the code.
Try subtracting the first Time.now from the second. Like so:
a = Time.now
sleep(3)
puts Time.now - a # about 3.0
This gives you a floating-point number of the seconds between the two times (and with that, the milliseconds).
I submit my example for consideration. This is how I call some code from a controller script in the tools I make. The scripts that do the work also need to accept parameters as well, so this example shows how to pass them. It does assume the script being called is in the same directory as the controller script (script making the call).
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$Computername,
[Parameter(Mandatory = $true)]
[DateTime]
$StartTime,
[Parameter(Mandatory = $true)]
[DateTime]
$EndTime
)
$ZAEventLogDataSplat = @{
"Computername" = $Computername
"StartTime" = $StartTime
"EndTime" = $EndTime
}
& "$PSScriptRoot\Get-ZAEventLogData.ps1" @ZAEventLogDataSplat
The above is a controller script that accepts 3 parameters. These are defined in the param block. The controller script then calls the script named Get-ZAEventLogData.ps1. For the sake of example, this script also accepts the same 3 parameters. When the controller script calls to the script that does the work, it needs to call it and pass the parameters. The above shows how I do it by splatting.
<shameless-plug>
Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here
Feel free to post any issues/suggestions here.
</shameless-plug>
this worked for me:
jQuery('form').attr("placeholder","Wert eingeben");
but now this don't work:
// Prioritize "important" elements on medium.
skel.on('+medium -medium', function() {
jQuery.prioritize(
'.important\\28 medium\\29',
skel.breakpoint('medium').active
);
});
I had the same issue after trying many combination I had this working note I have compatibility checked for intranet
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<head runat="server">
The long boring solution, which is not involved with CLI, you can manually navigate to:
your local repo folder ? .git folder (hidden) ? config file
then choose your text editor to open it and look for url located under the [remote "origin"] section.
Sometimes it is possible to have most of implementation hidden in cpp file, if you can extract common functionality foo all template parameters into non-template class (possibly type-unsafe). Then header will contain redirection calls to that class. Similar approach is used, when fighting with "template bloat" problem.
The below code works for me, for both accessing and changing a pixel value.
For accessing pixel's channel value :
for (int i = 0; i < image.cols; i++) {
for (int j = 0; j < image.rows; j++) {
Vec3b intensity = image.at<Vec3b>(j, i);
for(int k = 0; k < image.channels(); k++) {
uchar col = intensity.val[k];
}
}
}
For changing a pixel value of a channel :
uchar pixValue;
for (int i = 0; i < image.cols; i++) {
for (int j = 0; j < image.rows; j++) {
Vec3b &intensity = image.at<Vec3b>(j, i);
for(int k = 0; k < image.channels(); k++) {
// calculate pixValue
intensity.val[k] = pixValue;
}
}
}
`
Source : Accessing pixel value
In our case it was Windows-integrated authentication specified in the app's web.config
BUT the windows-auth module was not installed on the IIS machine at all.
Just adding another possible reason.
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside
I recently created a library that uses annotations to generate those type casting boilerplate code for you. https://github.com/zeroarst/callbackfragment
Here is an example. Click a TextView
on DialogFragment
triggers a callback to MainActivity
in onTextClicked
then grab the MyFagment
instance to interact with.
public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback, MyDialogFragment.DialogListener {
private static final String MY_FRAGM = "MY_FRAGMENT";
private static final String MY_DIALOG_FRAGM = "MY_DIALOG_FRAGMENT";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), MY_FRAGM)
.commit();
findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyDialogFragmentCallbackable.create().show(getSupportFragmentManager(), MY_DIALOG_FRAGM);
}
});
}
Toast mToast;
@Override
public void onClickButton(MyFragment fragment) {
if (mToast != null)
mToast.cancel();
mToast = Toast.makeText(this, "Callback from " + fragment.getTag() + " to " + this.getClass().getSimpleName(), Toast.LENGTH_SHORT);
mToast.show();
}
@Override
public void onTextClicked(MyDialogFragment fragment) {
MyFragment myFragm = (MyFragment) getSupportFragmentManager().findFragmentByTag(MY_FRAGM);
if (myFragm != null) {
myFragm.updateText("Callback from " + fragment.getTag() + " to " + myFragm.getTag());
}
}
}
Since the question on how to set fields mandatory pops up under each post, I wrote a small example on how to set fields as required:
public class ExampleDTO {
@NotNull
private String mandatoryParam;
private String optionalParam;
@DateTimeFormat(iso = ISO.DATE) //accept Dates only in YYYY-MM-DD
@NotNull
private LocalDate testDate;
public String getMandatoryParam() {
return mandatoryParam;
}
public void setMandatoryParam(String mandatoryParam) {
this.mandatoryParam = mandatoryParam;
}
public String getOptionalParam() {
return optionalParam;
}
public void setOptionalParam(String optionalParam) {
this.optionalParam = optionalParam;
}
public LocalDate getTestDate() {
return testDate;
}
public void setTestDate(LocalDate testDate) {
this.testDate = testDate;
}
}
//Add this to your rest controller class
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String testComplexObject (@Valid ExampleDTO e){
System.out.println(e.getMandatoryParam() + " " + e.getTestDate());
return "Does this work?";
}
Disclaimer: I'm the author of jgeXml.
jgexml has Node.js based utility xsd2json
which does a transformation between an XML schema (XSD) and a JSON schema file.
As with other options, it's not a 1:1 conversion, and you may need to hand-edit the output to improve the JSON schema validation, but it has been used to represent a complex XML schema inside an OpenAPI (swagger) definition.
A sample of the purchaseorder.xsd given in another answer is rendered as:
"PurchaseOrderType": {
"type": "object",
"properties": {
"shipTo": {
"$ref": "#/definitions/USAddress"
},
"billTo": {
"$ref": "#/definitions/USAddress"
},
"comment": {
"$ref": "#/definitions/comment"
},
"items": {
"$ref": "#/definitions/Items"
},
"orderDate": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}.*$"
}
},
They don't get submitted, because that's what it says in the W3C specification.
17.13.2 Successful controls
A successful control is "valid" for submission. [snip]
- Controls that are disabled cannot be successful.
In other words, the specification says that controls that are disabled are considered invalid and should not be submitted.
I'm currently in the process of building a single page application. Here is what I have thus far that I believe would be answering your question. I have a base template (base.html) that has a div with the ng-view
directive in it. This directive tells angular where to put the new content in. Note that I'm new to angularjs myself so I by no means am saying this is the best way to do it.
app = angular.module('myApp', []);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/home/', {
templateUrl: "templates/home.html",
controller:'homeController',
})
.when('/about/', {
templateUrl: "templates/about.html",
controller: 'aboutController',
})
.otherwise({
template: 'does not exists'
});
});
app.controller('homeController', [
'$scope',
function homeController($scope,) {
$scope.message = 'HOME PAGE';
}
]);
app.controller('aboutController', [
'$scope',
function aboutController($scope) {
$scope.about = 'WE LOVE CODE';
}
]);
base.html
<html>
<body>
<div id="sideMenu">
<!-- MENU CONTENT -->
</div>
<div id="content" ng-view="">
<!-- Angular view would show here -->
</div>
<body>
</html>
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
You can also use a TextView and set the background image to what you wanted in the ImageView
. Furthermore if you were using the ImageView
as a button you can set it to click-able
Here is some basic code for a TextView
that shows an image with text on top of it.
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/your_image"
android:text="your text here" />
I was receiving this error message, even though I had the max
settings set within the binding of my WCF service config file:
<basicHttpBinding>
<binding name="NewBinding1"
receiveTimeout="01:00:00"
sendTimeout="01:00:00"
maxBufferSize="2000000000"
maxReceivedMessageSize="2000000000">
<readerQuotas maxDepth="2000000000"
maxStringContentLength="2000000000"
maxArrayLength="2000000000"
maxBytesPerRead="2000000000"
maxNameTableCharCount="2000000000" />
</binding>
</basicHttpBinding>
It seemed as though these binding settings weren't being applied, thus the following error message:
IIS7 - (413) Request Entity Too Large when connecting to the service.
I realised that the name=""
attribute within the <service>
tag of the web.config
is not a free text field, as I thought it was. It is the fully qualified name of an implementation of a service contract as mentioned within this documentation page.
If that doesn't match, then the binding settings won't be applied!
<services>
<!-- The namespace appears in the 'name' attribute -->
<service name="Your.Namespace.ConcreteClassName">
<endpoint address="http://localhost/YourService.svc"
binding="basicHttpBinding" bindingConfiguration="NewBinding1"
contract="Your.Namespace.IConcreteClassName" />
</service>
</services>
I hope that saves someone some pain...
There is a nice CLI based tool for accessing MSSQL databases now.
It's called mssql-cli
and it's a bit similar to postgres' psql
.
Install for example via pip
(global installation, for a local one omit the sudo
part):
sudo pip install mssql-cli
I had a situation where I was parsing strings and the first two positions of the string in question would be the field names of a healthcare claims coding standard. So I would strip out the strings and get values for F4, UR and UQ or whatnot. This was great on one record or a few records for one user. But when I wanted to see hundreds of records and the values for all usersz it needed to be a PIVOT. This was wonderful especially for exporting lots of records to excel. The specific reporting request I had received was "every time someone submitted a claim for Benadryl, what value did they submit in fields F4, UR, and UQ. I had an OUTER APPLY that created the ColTitle and the value fields below
PIVOT(
min(value)
FOR ColTitle in([F4], [UR], [UQ])
)
I overcome this issue with if anybody interested. In myMain method i called my readasync method like
Dispatcher.BeginInvoke(new ThreadStart(() => ReadData()));
Everything is fine for me now.
Rather than locks, I suggest you look at long-running transactions, using v$transaction
. From there you can join to v$session
, which should give you an idea about the UI (try the program and machine columns) as well as the user.
Looks like you are out of stack memory. You may want to increase it as Davide stated. To do it in python code, you would need to run your "main()" using threading:
def main():
pass # write your code here
sys.setrecursionlimit(2097152) # adjust numbers
threading.stack_size(134217728) # for your needs
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()
Source: c1729's post on codeforces. Runing it with PyPy is a bit trickier.
Clean Build folder + Build
will clear any error you may have even after fixing your code.
If you add all your events with this snippet of code:
//put this somewhere in your JavaScript:
HTMLElement.prototype.addEvent = function(event, callback){
if(!this.events)this.events = {};
if(!this.events[event]){
this.events[event] = [];
var element = this;
this['on'+event] = function(e){
var events = element.events[event];
for(var i=0;i<events.length;i++){
events[i](e||event);
}
}
}
this.events[event].push(callback);
}
//use like this:
element.addEvent('change', function(e){...});
then you can just use element.on<EVENTNAME>()
where <EVENTNAME>
is the name of your event, and that will call all events with <EVENTNAME>
Try prepending the doublequote with a backslash in your expresssion:
sed 's/\"//g' [file name]
The method arrayList.size()
returns the number of items in the list - so if the index is greater than or equal to the size()
, it doesn't exist.
if(index >= myList.size()){
//index not exists
}else{
// index exists
}
Extract all gz files in current directory and its subdirectories:
find . -name "*.gz" | xargs gunzip
print $input."<hr>".ereg_replace('/&/', ':::', $input);
becomes
print $input."<hr>".preg_replace('/&/', ':::', $input);
More example :
$mytext = ereg_replace('[^A-Za-z0-9_]', '', $mytext );
is changed to
$mytext = preg_replace('/[^A-Za-z0-9_]/', '', $mytext );
You can use display: table-cell
property as in the following code:
div {
height: 100%;
display: table-cell;
vertical-align: middle;
}
Here is one that hard fails after 4 attempts, and waits 2 seconds between attempts. Change as you wish to get what you want form this one:
from time import sleep
for x in range(0, 4): # try 4 times
try:
# msg.send()
# put your logic here
str_error = None
except Exception as str_error:
pass
if str_error:
sleep(2) # wait for 2 seconds before trying to fetch the data again
else:
break
Here is an example with backoff:
from time import sleep
sleep_time = 2
num_retries = 4
for x in range(0, num_retries):
try:
# put your logic here
str_error = None
except Exception as str_error:
pass
if str_error:
sleep(sleep_time) # wait before trying to fetch the data again
sleep_time *= 2 # Implement your backoff algorithm here i.e. exponential backoff
else:
break
git commit --amend
and press Enter.git push --force example-branch
command to force push over the old commit.Source: https://help.github.com/articles/changing-a-commit-message/
tf.all_variables()
can get you the information you want.
Also, this commit made today in TensorFlow Learn that provides a function get_variable_names
in estimator that you can use to retrieve all variable names easily.
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
As it appears you have the values as text, and not the numeric True/False, then you can use either COUNTIF
or SUMPRODUCT
=IF(SUMPRODUCT(--(A2:D2="False")),"False","True")
=IF(COUNTIF(A3:D3,"False*"),"False","True")
delete from table where id <> 2
edit: to correct syntax for MySQL
I think you can use display: inline-block
on the element you want to center and set text-align: center;
on its parent. This definitely center the div on all screen sizes.
Here you can see a fiddle: http://jsfiddle.net/PwC4T/2/ I add the code here for completeness.
HTML
<div id="container">
<div id="main">
<div id="somebackground">
Hi
</div>
</div>
</div>
CSS
#container
{
text-align: center;
}
#main
{
display: inline-block;
}
#somebackground
{
text-align: left;
background-color: red;
}
For vertical centering, I "dropped" support for some older browsers in favour of display: table;
, which absolutely reduce code, see this fiddle: http://jsfiddle.net/jFAjY/1/
Here is the code (again) for completeness:
HTML
<body>
<div id="table-container">
<div id="container">
<div id="main">
<div id="somebackground">
Hi
</div>
</div>
</div>
</div>
</body>
CSS
body, html
{
height: 100%;
}
#table-container
{
display: table;
text-align: center;
width: 100%;
height: 100%;
}
#container
{
display: table-cell;
vertical-align: middle;
}
#main
{
display: inline-block;
}
#somebackground
{
text-align: left;
background-color: red;
}
The advantage of this approach? You don't have to deal with any percantage, it also handles correctly the <video>
tag (html5), which has two different sizes (one during load, one after load, you can't fetch the tag size 'till video is loaded).
The downside is that it drops support for some older browser (I think IE8 won't handle this correctly)
First you can use a Paginator. This is as simple as:
$allUsers = User::paginate(15);
$someUsers = User::where('votes', '>', 100)->paginate(15);
The variables will contain an instance of Paginator class. all of your data will be stored under data
key.
Or you can do something like:
Old versions Laravel.
Model::all()->take(10)->get();
Newer version Laravel.
Model::all()->take(10);
For more reading consider these links:
If your data resides on HDFS, perhaps the fastest approach is to use hadoop streaming. Apache Pig's COUNT UDF, operates on a bag, and therefore uses a single reducer to compute the number of rows. Instead you can manually set the number of reducers in a simple hadoop streaming script as follows:
$HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar -Dmapred.reduce.tasks=100 -input <input_path> -output <output_path> -mapper /bin/cat -reducer "wc -l"
Note that I manually set the number of reducers to 100, but you can tune this parameter. Once the map-reduce job is done, the result from each reducer is stored in a separate file. The final count of rows is the sum of numbers returned by all reducers. you can get the final count of rows as follows:
$HADOOP_HOME/bin/hadoop fs -cat <output_path>/* | paste -sd+ | bc
This is a UNIX permission problem. Do not use sudo
for cloning the repository. You don't have the same ssh keys as root and you shouldn't work as root anyway. Try ls -la
to find the permissions on the files and use chmod
(or sudo chown
) to fix them. Hope that helps.
Appspot.com callback's service isn't available. ipinfo.io seems to be working.
I did an extra step and retrieved all geo info using AngularJS. (Thanks to Ricardo) Check it out.
<div ng-controller="geoCtrl">
<p ng-bind="ip"></p>
<p ng-bind="hostname"></p>
<p ng-bind="loc"></p>
<p ng-bind="org"></p>
<p ng-bind="city"></p>
<p ng-bind="region"></p>
<p ng-bind="country"></p>
<p ng-bind="phone"></p>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular-route.min.js"></script>
<script>
'use strict';
var geo = angular.module('geo', [])
.controller('geoCtrl', ['$scope', '$http', function($scope, $http) {
$http.jsonp('http://ipinfo.io/?callback=JSON_CALLBACK')
.success(function(data) {
$scope.ip = data.ip;
$scope.hostname = data.hostname;
$scope.loc = data.loc; //Latitude and Longitude
$scope.org = data.org; //organization
$scope.city = data.city;
$scope.region = data.region; //state
$scope.country = data.country;
$scope.phone = data.phone; //city area code
});
}]);
</script>
Working page here: http://www.orangecountyseomarketing.com/projects/_ip_angularjs.html
0755
= User:rwx
Group:r-x
World:r-x
0750
= User:rwx
Group:r-x
World:---
(i.e. World: no access)
r = read
w = write
x = execute (traverse for directories)
After trying few answers they are either not related to my project or , I have tried cleaning and rebuilding (https://stackoverflow.com/a/48760966/8463813). But it didn't work for me directly. I have compared it with older version of code, in which i observed some library files(jars and aars in External Libraries directory) are missing. Tried Invalidate Cache and Restart worked, which created all the libraries and working fine.
The only thing I could find said first try and do a VS-Repair. If that doesn't work then do this.
Restart Windows and in safe mode, run devenv /safemode in Visual Studio 2005 Command Prompt. If in safe mode this issue disappeared, the cause should be third-party applications, services or Visual Studio Add-ins. Please also try devenv /resetsettings or devenv /setup in Command Prompt.
As a kind of simple solution you can use temp TreeMap if you need just a final result:
TreeMap<String, Integer> sortedMap = new TreeMap<String, Integer>();
for (Map.Entry entry : map.entrySet()) {
sortedMap.put((String) entry.getValue(), (Integer)entry.getKey());
}
This will get you strings sorted as keys of sortedMap.
I tried all the solutions here, but to no avail. Eventually, I solved it by opening the new csproj file and manually added the following section:
<Reference Include="System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<HintPath>..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll</HintPath>
</Reference>
Use quotes!
cd "Name of Directory"
Or you can go to the file explorer and click "copy path" in the top left corner!
On Windows:-
Go to File -> Settings.
And open the 'Build,Execution,Deployment'
. Then open the
Build Tools -> Gradle
Then uncheck -> Offline work on the right.
Click the OK button.
Then Rebuild the Project.
On Mac OS:-
go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image
[
& "C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode
or
[System.Diagnostics.Process]::Start("C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe", "C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode")
UPDATE: sorry I missed "(I invoked the command using the "&" operator)" sentence. I had this problem when I was evaluating the path dynamically. Try Invoke-Expression construction:
Invoke-Expression "& `"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe`" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode"
You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
You need to override the color:
a { color:red } /* Globally */
/* Each state */
a:visited { text-decoration: none; color:red; }
a:hover { text-decoration: none; color:blue; }
a:focus { text-decoration: none; color:yellow; }
a:hover, a:active { text-decoration: none; color:black }
If you use json_decode($string, true)
, you will get no objects, but everything as an associative or number indexed array. Way easier to handle, as the stdObject provided by PHP is nothing but a dumb container with public properties, which cannot be extended with your own functionality.
$array = json_decode($string, true);
echo $array['trends'][0]['name'];
public - The members (Functions & Variables) declared as public can be accessed from anywhere.
private - Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be considered as private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber.
protected - Protected members can be accessed only from the child classes.
internal - It can be accessed only within the same assembly.
protected internal - It can be accessed within the same assembly as well as in derived class.
I just had this issue, and was able to work around it.
First, connect to the MySQL database with an older client that doesn't mind old_passwords. Connect using the user that your script will be using.
Run these queries:
SET SESSION old_passwords=FALSE;
SET PASSWORD = PASSWORD('[your password]');
In your PHP script, change your mysql_connect function to include the client flag 1:
define('CLIENT_LONG_PASSWORD', 1);
mysql_connect('[your server]', '[your username]', '[your password]', false, CLIENT_LONG_PASSWORD);
This allowed me to connect successfully.
Edit: as per Garland Pope's comment, it may not be necessary to set CLIENT_LONG_PASSWORD manually any more in your PHP code as of PHP 5.4!
Edit: courtesy of Antonio Bonifati, a PHP script to run the queries for you:
<?php const DB = [ 'host' => '...', # localhost may not work on some hosting
'user' => '...',
'pwd' => '...', ];
if (!mysql_connect(DB['host'], DB['user'], DB['pwd'])) {
die(mysql_error());
} if (!mysql_query($query = 'SET SESSION old_passwords=FALSE')) {
die($query);
} if (!mysql_query($query = "SET PASSWORD = PASSWORD('" . DB['pwd'] . "')")) {
die($query);
}
echo "Excellent, mysqli will now work";
?>
You have to open and close your class with { ... }
like:
public class mod_MyMod extends BaseMod
{
public String Version()
{
return "1.2_02";
}
public void AddRecipes(CraftingManager recipes)
{
recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
"#", Character.valueOf('#'), Block.dirt });
}
}
Posts abound regarding this topic, and to help others save hours of trying different solutions, here is the final result of my hours of tinkering.
The three solutions around the internet at the moment are: rubysspi apserver cntlm
rubysspi only works from a Windows machine, AFAIK, as it relies on the Win32Api library. So if you are on a Windows box trying to run through a proxy, this is the solution for you. If you are on a Linux distro, you're out of luck.
apserver seems to be a dead project. The link listed in the posts I've seen lead to 404 page on sourceforge. I search for "apserver" on sourceforge returns nothing.
The sourceforge link for cntlm that I've seen redirects to http://cntlm.awk.cz/, but that times out. A search on sourceforge turns up this link, which does work: http://sourceforge.net/projects/cntlm/
After downloading and configuring cntlm I have managed to install a gem through the proxy, so this seems to be the best solution for Linux distros.
wt = tt - cpu tm.
Tt = cpu tm + wt.
Where wt
is a waiting time and tt
is turnaround time. Cpu time is also called burst time.
These are positional arguments of the script.
Executing
./script.sh Hello World
Will make
$0 = ./script.sh
$1 = Hello
$2 = World
Note
If you execute ./script.sh
, $0
will give output ./script.sh
but if you execute it with bash script.sh
it will give output script.sh
.
No need to edit any database directly, there is a command for it :)
svc wifi [enable|disable]
You might want to look at csounds, also. It has several API's, including Python. It might be able to interact with an A-D interface and gather sound samples.
There is one more solution to set column Full text to true.
These solution for example didn't work for me
ALTER TABLE news ADD FULLTEXT(headline, story);
My solution.
NEXT STEPS
Refresh
Version of mssql 2014
I think list comprehension is one of the cleanest ways that doesn't need any additional imports:
>>> d={"foo": 1, "bar": 2, "baz": 3}
>>> a = [d.get(k) for k in ["foo", "bar", "baz"]]
>>> a
[1, 2, 3]
Of if you want the values as individual variables then use multiple-assignment:
>>> a,b,c = [d.get(k) for k in ["foo", "bar", "baz"]]
>>> a,b,c
(1, 2, 3)
Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.
You've got a couple of choices;
Calling the intent to add an event on the calendar
This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=DAILY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
Or the more complicated one:
Get a reference to the calendar with this method
(It is highly recommended not to use this method, because it could break on newer Android versions):
private String getCalendarUriBase(Activity act) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
and add an event and a reminder this way:
// get calendar
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
ContentResolver cr = getContentResolver();
// event insert
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", "Reminder Title");
values.put("allDay", 0);
values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
values.put("description", "Reminder description");
values.put("visibility", 0);
values.put("hasAlarm", 1);
Uri event = cr.insert(EVENTS_URI, values);
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
values.put( "method", 1 );
values.put( "minutes", 10 );
cr.insert( REMINDERS_URI, values );
You'll also need to add these permissions to your manifest for this method:
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
Update: ICS Issues
The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.
More infos about this can be found at this blog post.
For the postgrersql10
I have solved it with
yum install postgresql10-contrib
Don't forget to activate extensions in postgresql.conf
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = all
then of course restart
systemctl restart postgresql-10.service
all of the needed extensions you can find here
/usr/pgsql-10/share/extension/
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
I tend to avoid enums, because they are not extensible. To stay with the example of the OP, if A is in a library and B in your own code, you can't extend A if it is an enum. This is how I sometimes replace enums:
// access like enum: A.a
public class A {
public static final A a = new A();
public static final A b = new A();
public static final A c = new A();
/*
* In case you need to identify your constant
* in different JVMs, you need an id. This is the case if
* your object is transfered between
* different JVM instances (eg. save/load, or network).
* Also, switch statements don't work with
* Objects, but work with int.
*/
public static int maxId=0;
public int id = maxId++;
public int getId() { return id; }
}
public class B extends A {
/*
* good: you can do like
* A x = getYourEnumFromSomeWhere();
* if(x instanceof B) ...;
* to identify which enum x
* is of.
*/
public static final A d = new A();
}
public class C extends A {
/* Good: e.getId() != d.getId()
* Bad: in different JVMs, C and B
* might be initialized in different order,
* resulting in different IDs.
* Workaround: use a fixed int, or hash code.
*/
public static final A e = new A();
public int getId() { return -32489132; };
}
There are some pits to avoid, see the comments in the code. Depending on your needs, this is a solid, extensible alternative to enums.
Sometimes two classes may have some parameter names in common. In that case, you can't pop the key-value pairs off of **kwargs
or remove them from *args
. Instead, you can define a Base
class which unlike object
, absorbs/ignores arguments:
class Base(object):
def __init__(self, *args, **kwargs): pass
class A(Base):
def __init__(self, *args, **kwargs):
print "A"
super(A, self).__init__(*args, **kwargs)
class B(Base):
def __init__(self, *args, **kwargs):
print "B"
super(B, self).__init__(*args, **kwargs)
class C(A):
def __init__(self, arg, *args, **kwargs):
print "C","arg=",arg
super(C, self).__init__(arg, *args, **kwargs)
class D(B):
def __init__(self, arg, *args, **kwargs):
print "D", "arg=",arg
super(D, self).__init__(arg, *args, **kwargs)
class E(C,D):
def __init__(self, arg, *args, **kwargs):
print "E", "arg=",arg
super(E, self).__init__(arg, *args, **kwargs)
print "MRO:", [x.__name__ for x in E.__mro__]
E(10)
yields
MRO: ['E', 'C', 'A', 'D', 'B', 'Base', 'object']
E arg= 10
C arg= 10
A
D arg= 10
B
Note that for this to work, Base
must be the penultimate class in the MRO.
Try to add export PATH=$PATH:/home/me/play
in ~/.bashrc file.
I had the same problem on Debian, yarn was the solution for me.
So within the render
method comments are allowed but in order to use them within JSX, you have to wrap them in braces and use multi-line style comments.
<div className="dropdown">
{/* whenClicked is a property not an event, per se. */}
<Button whenClicked={this.handleClick} className="btn-default" title={this.props.title} subTitleClassName="caret"></Button>
<UnorderedList />
</div>
You can read more about how comments work in JSX here
This example program illustrates initialization of an array of C strings.
#include <stdio.h>
const char * array[] = {
"First entry",
"Second entry",
"Third entry",
};
#define n_array (sizeof (array) / sizeof (const char *))
int main ()
{
int i;
for (i = 0; i < n_array; i++) {
printf ("%d: %s\n", i, array[i]);
}
return 0;
}
It prints out the following:
0: First entry
1: Second entry
2: Third entry
With a Swift slant and want a bare-bones example, here is my go-to method for passing data if you are using a segue to get around.
It is similar to the above but without the buttons, labels and such. Just simply passing data from one view to the next.
Setup The Storyboard
There are three parts.
This is a very simple view layout with a segue between them.
Here is the setup for the sender
Here is the setup for the receiver.
Lastly, the setup for the segue.
The View Controllers
We are keeping this simple so no buttons and not actions. We are simply moving data from the sender to the receiver when the application loads and then outputting the transmitted value to the console.
This page takes the initially loaded value and passes it along.
import UIKit
class ViewControllerSender: UIViewController {
// THE STUFF - put some information into a variable
let favoriteMovie = "Ghost Busters"
override func viewDidAppear(animated: Bool) {
// PASS IDENTIFIER - go to the receiving view controller.
self.performSegueWithIdentifier("goToReciever", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// GET REFERENCE - ...to the receiver view.
var viewControllerReceiver = segue.destinationViewController as? ViewControllerReceiver
// PASS STUFF - pass the variable along to the target.
viewControllerReceiver!.yourFavMovie = self.favoriteMovie
}
}
This page just sends the value of the variable to the console when it loads. By this point, our favorite movie should be in that variable.
import UIKit
class ViewControllerReceiver: UIViewController {
// Basic empty variable waiting for you to pass in your fantastic favorite movie.
var yourFavMovie = ""
override func viewDidLoad() {
super.viewDidLoad()
// And now we can view it in the console.
println("The Movie is \(self.yourFavMovie)")
}
}
That is how you can tackle it if you want to use a segue and you don't have your pages under a navigation controller.
Once it is run, it should switch to the receiver view automatically and pass the value from the sender to the receiver, displaying the value in the console.
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
This combination of properties helped for me:
display: inline-block;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: normal;
line-break: strict;
hyphens: none;
-webkit-hyphens: none;
-moz-hyphens: none;
You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.
I have added a line in list item like below
<View
android:id="@+id/divider"
android:layout_width="match_parent"
android:layout_height="1px"
android:background="@color/dividerColor"/>
1px will draw the thin line.
If you want to hide the divider for the last row then
divider.setVisiblity(View.GONE);
on the onBindViewHolder for the last list Item.
I had this problem while inheriting from ApiController instead of the regular Controller class. I solved it by using var container = Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);
I followed this thread How to get Request Querystring values?
EDIT: After trying to filter through the container I was getting odd error messages. After going to my project properties and I unchecked the Optimize Code checkbox which changed so that all of a sudden the parameters in my controller where filled up from the url as I wanted.
Hopefully this will help someone with the same problem..
I had the same issue, luckily I found the below code
@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )
Assuming your code is inside an MVC controller:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
From the Controller
base class, you can get the IClaimsPrincipal
from the User
property
System.Security.Claims.ClaimsPrincipal currentUser = this.User;
You can check the claims directly (without a round trip to the database):
bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:
Other fields can be fetched from the database's User entity:
Get the user manager using dependency injection
private UserManager<ApplicationUser> _userManager;
//class constructor
public MyController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
And use it:
var user = await _userManager.GetUserAsync(User);
var email = user.Email;
If it's just for viewing data, I use simple foreach or even aspRepeater. For editing I build specialized views and actions. Didn't like webforms GridView inline edit capabilities anyway, this is kinda much clearer and better - one view for viewing and another for edit/new.
Unfortunately, none of the solution listed here helped me to resolve this issue. I fixed this issue by using http://127.0.0.1 (ip address) instead of http://localhost. A quick little hack to work with angular development with chrome browser.
You can create table variables:
DECLARE @result1 TABLE (a INT, b INT, c INT)
INSERT INTO @result1
SELECT a, b, c
FROM table1
SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1
This should be fine for what you need.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
Use sudo pip3 install jupyter
for installing jupyter for python3 and sudo pip install jupyter
for installing jupyter notebook for python2. Then, you can call ipython kernel install
command to enable both types of notebook to choose from in jupyter notebook.
According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData});
Codetoffel answer does work just fine for me though.
Try this below code it is also works well in angular 2
<span>{{current_date | date: 'yyyy-MM-dd'}}</span>
If your app is a Scala app, it must have a build.sbt
in the root directory, and that file must be checked into Git. You can confirm this by running:
$ git ls-files build.sbt
If that file exists and is checked into Git, try running this command:
$ heroku buildpacks:set heroku/scala
If I understand correctly, you want to have one class implement multiple of those interfaces with different input/output parameters? This will not work in Java, because the generics are implemented via erasure.
The problem with the Java generics is that the generics are in fact nothing but compiler magic. At runtime, the classes do not keep any information about the types used for generic stuff (class type parameters, method type parameters, interface type parameters). Therefore, even though you could have overloads of specific methods, you cannot bind those to multiple interface implementations which differ in their generic type parameters only.
In general, I can see why you think that this code has a smell. However, in order to provide you with a better solution, it would be necessary to know a little more about your requirements. Why do you want to use a generic interface in the first place?
Sure, you can use JS's foreach.
for (var k in result) {
something(result[k])
}
Many right answers but in case you want it in a float, directly, without using regex:
x= '$123.45M'
float(''.join(c for c in x if (c.isdigit() or c =='.'))
123.45
You can change the point for a comma depending on your needs.
change for this if you know your number is an integer
x='$1123'
int(''.join(c for c in x if c.isdigit())
1123
if ($inputs['type'] == 'attach') {
The code is valid, but it expects the function parameter $inputs
to be an array. The "Illegal string offset" warning when using $inputs['type']
means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type'
is not suitable.)
So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.
However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type'
to 0
, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)
You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs);
in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:
if (is_array($inputs) && $inputs['type'] == 'attach') {
BigInteger would only be used if you know it will not be a decimal and there is a possibility of the long data type not being large enough. BigInteger has no cap on its max size (as large as the RAM on the computer can hold).
From here.
It is implemented using an int[]
:
110 /**
111 * The magnitude of this BigInteger, in <i>big-endian</i> order: the
112 * zeroth element of this array is the most-significant int of the
113 * magnitude. The magnitude must be "minimal" in that the most-significant
114 * int ({@code mag[0]}) must be non-zero. This is necessary to
115 * ensure that there is exactly one representation for each BigInteger
116 * value. Note that this implies that the BigInteger zero has a
117 * zero-length mag array.
118 */
119 final int[] mag;
From the source
From the Wikipedia article Arbitrary-precision arithmetic:
Several modern programming languages have built-in support for bignums, and others have libraries available for arbitrary-precision integer and floating-point math. Rather than store values as a fixed number of binary bits related to the size of the processor register, these implementations typically use variable-length arrays of digits.
When you use useState
, you can get an update method for the state item:
const [theArray, setTheArray] = useState(initialArray);
then, when you want to add a new element, you use that function and pass in the new array or a function that will create the new array. Normally the latter, since state updates are asynchronous and sometimes batched:
setTheArray(oldArray => [...oldArray, newElement]);
Sometimes you can get away without using that callback form, if you only update the array in handlers for certain specific user events like click
(but not like mousemove
):
setTheArray([...theArray, newElement]);
The events for which React ensures that rendering is flushed are the "discrete events" listed here.
Live Example (passing a callback into setTheArray
):
const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray(oldArray => [...oldArray, `Entry ${oldArray.length}`]);
};
return [
<input type="button" onClick={addEntryClick} value="Add" />,
<div>{theArray.map(entry =>
<div>{entry}</div>
)}
</div>
];
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);
_x000D_
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>
_x000D_
Because the only update to theArray
in there is the one in a click
event (one of the "discrete" events), I could get away with a direct update in addEntry
:
const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray([...theArray, `Entry ${theArray.length}`]);
};
return [
<input type="button" onClick={addEntryClick} value="Add" />,
<div>{theArray.map(entry =>
<div>{entry}</div>
)}
</div>
];
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);
_x000D_
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>
_x000D_
If you really want an iterator-free solution, you can use numpy and its array round function.
import numpy as np
myList = list(np.around(np.array(myList),2))
The first step is to make P2 reference P1 by doing the following
Next you'll need to make sure that the classes in P1 are accessible to P2. The easiest way is to make them public
.
public class MyType { ... }
Now you should be able to use them in P2 via their fully qualified name. Assuming the namespace of P1 is Project1 then the following would work
Project1.MyType obj = new Project1.MyType();
The preferred way though is to add a using for Project1
so you can use the types without qualification
using Project1;
...
public void Example() {
MyType obj = new MyType();
}
Here is the answer to the question here
Actually we have to get it from the sharable ContentProvider of Camera Application.
EDIT . Copying answer that worked for me
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Okay lots of posts here, none of them helped me, days and days of google, and still no further I got to the point the wr-writing the whole app from scratch, and then I noticed this little nugget in my Web.confg
<httpCookies requireSSL="false" domain="*.localLookup.net"/>
Now I don't know why I added it however I have since noticed, its ignored in debug mode and not in a production mode (IE Installed to IIS Somewhere)
For me the solution was one of 2 options, since I don't remember why I added it I cant be sure other things don't depend on it, and second the domain name must be all lower case and a TLD not like ive done in *.localLookup.net
Maybe it helps maybe it don't. I hope it does help someone
I went through a similar issue. If you consider your "YeagerTechResources.Resources", it means that your Resources.resx is at the root folder of your project.
Be careful to include the full path eg : "project\subfolder(s)\file[.resx]" to the ResourceManager constructor.
Change the Encoding to UTF-8 while parsing .This will remove the special characters
multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.
The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).
The payload passed looks something like this:
Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”file”; filename=”captcha”
Content-Type:
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”action”
submit
-----WebKitFormBoundary7MA4YWxkTrZu0gW--
On the webservice side, it's consumed in @Consumes("multipart/form-data") form.
Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.
I converted the 'fast quick sort' algorithm to VBA, if anyone else wants it.
I have it optimized to run on an array of Int/Longs but it should be simple to convert it to one that works on arbitrary comparable elements.
Private Sub QuickSort(ByRef a() As Long, ByVal l As Long, ByVal r As Long)
Dim M As Long, i As Long, j As Long, v As Long
M = 4
If ((r - l) > M) Then
i = (r + l) / 2
If (a(l) > a(i)) Then swap a, l, i '// Tri-Median Methode!'
If (a(l) > a(r)) Then swap a, l, r
If (a(i) > a(r)) Then swap a, i, r
j = r - 1
swap a, i, j
i = l
v = a(j)
Do
Do: i = i + 1: Loop While (a(i) < v)
Do: j = j - 1: Loop While (a(j) > v)
If (j < i) Then Exit Do
swap a, i, j
Loop
swap a, i, r - 1
QuickSort a, l, j
QuickSort a, i + 1, r
End If
End Sub
Private Sub swap(ByRef a() As Long, ByVal i As Long, ByVal j As Long)
Dim T As Long
T = a(i)
a(i) = a(j)
a(j) = T
End Sub
Private Sub InsertionSort(ByRef a(), ByVal lo0 As Long, ByVal hi0 As Long)
Dim i As Long, j As Long, v As Long
For i = lo0 + 1 To hi0
v = a(i)
j = i
Do While j > lo0
If Not a(j - 1) > v Then Exit Do
a(j) = a(j - 1)
j = j - 1
Loop
a(j) = v
Next i
End Sub
Public Sub sort(ByRef a() As Long)
QuickSort a, LBound(a), UBound(a)
InsertionSort a, LBound(a), UBound(a)
End Sub
The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.
Your criticism is entirely justified.
I discuss this problem in detail here:
Closing over the loop variable considered harmful
Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?
The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.
I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.
The for
loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.
IIS now has
Idle Time-out Action : Suspend
setting
Suspending is just freezes the process and it is much more efficient than the destroying the process.
Finally I got solution using Jackson library along with Spring MVC. I got this solution from an example of Journal Dev( http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program )
So, the code changes I have done are:
I didn't made any changes to my REST service controller. By default it converts into JSON.
It looks like your 'trainData' is a list of strings:
['-214' '-153' '-58' ..., '36' '191' '-37']
Change your 'trainData' to a numeric type.
import numpy as np
np.array(['1','2','3']).astype(np.float)
libsysfs does look potentially useful, but not directly from a shell script. There's a program that comes with it called systool which will do what you want, though it may be easier to just look in /sys directly rather than using another program to do it for you.
It's the same. Your international format is already correct, and is recommended for use in all cases, where possible.
Try this. The scope of local variables defined by "template" directive.
<table>
<template ngFor let-group="$implicit" [ngForOf]="groups">
<tr>
<td>
<h2>{{group.name}}</h2>
</td>
</tr>
<tr *ngFor="let item of group.items">
<td>{{item}}</td>
</tr>
</template>
</table>
Some extend
functions in third party libraries are more complex than others. Knockout.js for instance contains a minimally simple one that doesn't have some of the checks that jQuery's does:
function extend(target, source) {
if (source) {
for(var prop in source) {
if(source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
}
return target;
}
If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:
I am using the with statement in this example, which closes the file after the with
block is terminated - either normally when the last command finishes executing, or by an exception.
def inplace_change(filename, old_string, new_string):
# Safely read the input filename using 'with'
with open(filename) as f:
s = f.read()
if old_string not in s:
print('"{old_string}" not found in {filename}.'.format(**locals()))
return
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
s = s.replace(old_string, new_string)
f.write(s)
It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with
statement.
The query string that I used to to escape the new line character in JS :
LOAD DATA LOCAL INFILE 'Data.csv' INTO TABLE DEMO FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS;
This involves new ES6 syntax - Template Literals `` and I tried changing '\n' to '\r\n' and worked perfectly in my case.
PS: This example is my query to upload CSV data into mysql DB.
I always use this.It send form data using ajax
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
}
});
});
I have answered this question here..Covariant virtual functions return type problem
See if it helps for some one.
import request
response = requests.get("url/api that you want to hit", verify="path to ssl certificate")
For me the problem was that none of the above answers completely helped me but gave me the right direction to look at.
For sure, SSL certificate is needed but when you are behind the company's firewall then publicly available certificates might not help. You might need to reach out to the IT department of your company to obtain the certificate as each company uses special certificate from the security provider they have contracted the services from. And place it in a folder and pass the path to that folder as an argument to verify parameter.
For me even after trying all the above solutions and using the wrong certificate I was not able to make it work. So just remember for those who are behind company's firewall to obtain the right certificate. It can make a difference between success and failure of your request call.
In my case I placed the certificate in the following path and it worked like magic.
C:\Program Files\Common Files\ssl
You could also refer https://2.python-requests.org/en/master/user/advanced/#id3 which talks about ssl verification
You can achieve with below queries
select extract(xmltype(xml), '//fax/text()').getStringVal() from mytab;
select extractvalue(xmltype(xml), '//fax') from mytab;
<?php
$time_now=mktime(date('h')+5,date('i')+30,date('s'));
$dateTime = date('d_m_Y h:i:s A',$time_now);
echo $dateTime;
?>
While this is definitely not the optimal solution to the problem, it is another potential solution which I thought some people might find interesting:
/**
* Treat the bst as a sorted list in descending order and find the element
* in position k.
*
* Time complexity BigO ( n^2 )
*
* 2n + sum( 1 * n/2 + 2 * n/4 + ... ( 2^n-1) * n/n ) =
* 2n + sigma a=1 to n ( (2^(a-1)) * n / 2^a ) = 2n + n(n-1)/4
*
* @param t The root of the binary search tree.
* @param k The position of the element to find.
* @return The value of the element at position k.
*/
public static int kElement2( Node t, int k ) {
int treeSize = sizeOfTree( t );
return kElement2( t, k, treeSize, 0 ).intValue();
}
/**
* Find the value at position k in the bst by doing an in-order traversal
* of the tree and mapping the ascending order index to the descending order
* index.
*
*
* @param t Root of the bst to search in.
* @param k Index of the element being searched for.
* @param treeSize Size of the entire bst.
* @param count The number of node already visited.
* @return Either the value of the kth node, or Double.POSITIVE_INFINITY if
* not found in this sub-tree.
*/
private static Double kElement2( Node t, int k, int treeSize, int count ) {
// Double.POSITIVE_INFINITY is a marker value indicating that the kth
// element wasn't found in this sub-tree.
if ( t == null )
return Double.POSITIVE_INFINITY;
Double kea = kElement2( t.getLeftSon(), k, treeSize, count );
if ( kea != Double.POSITIVE_INFINITY )
return kea;
// The index of the current node.
count += 1 + sizeOfTree( t.getLeftSon() );
// Given any index from the ascending in order traversal of the bst,
// treeSize + 1 - index gives the
// corresponding index in the descending order list.
if ( ( treeSize + 1 - count ) == k )
return (double)t.getNumber();
return kElement2( t.getRightSon(), k, treeSize, count );
}
a much more practical way for those who do not want to use regex:
$data = filter_var($data, FILTER_SANITIZE_NUMBER_INT);
note: it works with phone numbers too.
You should use a with statement to qualify both your Rows
and Columns
counts. This will prevent any errors while working with older pre 2007 and newer 2007 Excel Workbooks.
Last Column
With Sheets("Sheet2")
.Cells(1, .Columns.Count).End(xlToLeft).Column
End With
Last Row
With Sheets("Sheet2")
.Range("A" & .Rows.Count).End(xlUp).Row
End With
Or
With Sheets("Sheet2")
.Cells(.Rows.Count, 1).End(xlUp).Row
End With
In your controller use:
var path = HttpContext.Server.MapPath("~/Data/data.html");
This allows you to test the controller with Moq like so:
var queryString = new NameValueCollection();
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(r => r.QueryString).Returns(queryString);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
var server = new Mock<HttpServerUtilityBase>();
server.Setup(m => m.MapPath("~/Data/data.html")).Returns("path/to/test/data");
mockHttpContext.Setup(m => m.Server).Returns(server.Object);
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
var controller = new MyTestController();
controller.ControllerContext = mockControllerContext.Object;
To make it very simple with minimum interface & please focus "//1":
class FactoryProgram
{
static void Main()
{
object myType = Program.MyFactory("byte");
Console.WriteLine(myType.GetType().Name);
myType = Program.MyFactory("float"); //3
Console.WriteLine(myType.GetType().Name);
Console.ReadKey();
}
static object MyFactory(string typeName)
{
object desiredType = null; //1
switch (typeName)
{
case "byte": desiredType = new System.Byte(); break; //2
case "long": desiredType = new System.Int64(); break;
case "float": desiredType = new System.Single(); break;
default: throw new System.NotImplementedException();
}
return desiredType;
}
}
Here important points: 1. Factory & AbstractFactory mechanisms must use inheritance (System.Object-> byte, float ...); so if you have inheritance in program then Factory(Abstract Factory would not be there most probably) is already there by design 2. Creator (MyFactory) knows about concrete type so returns concrete type object to caller(Main); In abstract factory return type would be an Interface.
interface IVehicle { string VehicleName { get; set; } }
interface IVehicleFactory
{
IVehicle CreateSingleVehicle(string vehicleType);
}
class HondaFactory : IVehicleFactory
{
public IVehicle CreateSingleVehicle(string vehicleType)
{
switch (vehicleType)
{
case "Sports": return new SportsBike();
case "Regular":return new RegularBike();
default: throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", vehicleType));
}
}
}
class HeroFactory : IVehicleFactory
{
public IVehicle CreateSingleVehicle(string vehicleType)
{
switch (vehicleType)
{
case "Sports": return new SportsBike();
case "Scooty": return new Scooty();
case "DarkHorse":return new DarkHorseBike();
default: throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", vehicleType));
}
}
}
class RegularBike : IVehicle { public string VehicleName { get { return "Regular Bike- Name"; } set { VehicleName = value; } } }
class SportsBike : IVehicle { public string VehicleName { get { return "Sports Bike- Name"; } set { VehicleName = value; } } }
class RegularScooter : IVehicle { public string VehicleName { get { return "Regular Scooter- Name"; } set { VehicleName = value; } } }
class Scooty : IVehicle { public string VehicleName { get { return "Scooty- Name"; } set { VehicleName = value; } } }
class DarkHorseBike : IVehicle { public string VehicleName { get { return "DarkHorse Bike- Name"; } set { VehicleName = value; } } }
class Program
{
static void Main(string[] args)
{
IVehicleFactory honda = new HondaFactory(); //1
RegularBike hondaRegularBike = (RegularBike)honda.CreateSingleVehicle("Regular"); //2
SportsBike hondaSportsBike = (SportsBike)honda.CreateSingleVehicle("Sports");
Console.WriteLine("******* Honda **********"+hondaRegularBike.VehicleName+ hondaSportsBike.VehicleName);
IVehicleFactory hero = new HeroFactory();
DarkHorseBike heroDarkHorseBike = (DarkHorseBike)hero.CreateSingleVehicle("DarkHorse");
SportsBike heroSportsBike = (SportsBike)hero.CreateSingleVehicle("Sports");
Scooty heroScooty = (Scooty)hero.CreateSingleVehicle("Scooty");
Console.WriteLine("******* Hero **********"+heroDarkHorseBike.VehicleName + heroScooty.VehicleName+ heroSportsBike.VehicleName);
Console.ReadKey();
}
}
Important points: 1. Requirement: Honda would create "Regular", "Sports" but Hero would create "DarkHorse", "Sports" and "Scooty". 2. why two interfaces? One for manufacturer type(IVehicleFactory) and another for product factory(IVehicle); other way to understand 2 interfaces is abstract factory is all about creating related objects 2. The catch is the IVehicleFactory's children returning and IVehicle(instead of concrete in factory); so I get parent variable(IVehicle); then I create actual concrete type by calling CreateSingleVehicle and then casting parent object to actual child object. What would happen if I do RegularBike heroRegularBike = (RegularBike)hero.CreateSingleVehicle("Regular");
; you will get ApplicationException and that's why we need generic abstract factory which I would explain if required. Hope it helps from beginner to intermediate audience.
The same as you, I was looking for a way to map users/groups from host to docker containers and this is the shortest way I've found so far:
version: "3"
services:
my-service:
.....
volumes:
# take uid/gid lists from host
- /etc/passwd:/etc/passwd:ro
- /etc/group:/etc/group:ro
# mount config folder
- path-to-my-configs/my-service:/etc/my-service:ro
.....
This is an extract from my docker-compose.yml.
The idea is to mount (in read-only mode) users/groups lists from the host to the container thus after the container starts up it will have the same uid->username (as well as for groups) matchings with the host. Now you can configure user/group settings for your service inside the container as if it was working on your host system.
When you decide to move your container to another host you just need to change user name in service config file to what you have on that host.
I did some development with Mifare Classic (ISO 14443A) cards about 7-8 years ago. You can read and write to all sectors of the card, IIRC the only data you can't change is the serial number. Back then we used a proprietary library from Philips Semiconductors. The command interface to the card was quite alike the ISO 7816-4 (used with standard Smart Cards).
I'd recomment that you look at the OpenPCD platform if you are into development.
This is also of interest regarding the cryptographic functions in some RFID cards.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
Log in to one machine
$ scp -r /path/to/top/directory user@server:/path/to/copy