Freshly-made function for PHP 5.2 compatibility, if you need the decoded data on success:
function try_json_decode( $json, & $success = null ){
// non-strings may cause warnings
if( !is_string( $json )){
$success = false;
return $json;
}
$data = json_decode( $json );
// output arg
$success =
// non-null data: success!
$data !== null ||
// null data from 'null' json: success!
$json === 'null' ||
// null data from ' null ' json padded with whitespaces: success!
preg_match('/^\s*null\s*$/', $json );
// return decoded or original data
return $success ? $data : $json;
}
Usage:
$json_or_not = ...;
$data = try_json_decode( $json_or_not, $success );
if( $success )
process_data( $data );
else what_the_hell_is_it( $data );
Some tests:
var_dump( try_json_decode( array(), $success ), $success );
// ret = array(0){}, $success == bool(false)
var_dump( try_json_decode( 123, $success ), $success );
// ret = int(123), $success == bool(false)
var_dump( try_json_decode(' ', $success ), $success );
// ret = string(6) " ", $success == bool(false)
var_dump( try_json_decode( null, $success ), $success );
// ret = NULL, $success == bool(false)
var_dump( try_json_decode('null', $success ), $success );
// ret = NULL, $success == bool(true)
var_dump( try_json_decode(' null ', $success ), $success );
// ret = NULL, $success == bool(true)
var_dump( try_json_decode(' true ', $success ), $success );
// ret = bool(true), $success == bool(true)
var_dump( try_json_decode(' "hello" ', $success ), $success );
// ret = string(5) "hello", $success == bool(true)
var_dump( try_json_decode(' {"a":123} ', $success ), $success );
// ret = object(stdClass)#2 (1) { ["a"]=> int(123) }, $success == bool(true)
You need to read from the configuration section manually before your code returns a JsonResult object. Simply read from web.config in single line:
var jsonResult = Json(resultsForAjaxUI);
jsonResult.MaxJsonLength = (ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as System.Web.Configuration.ScriptingJsonSerializationSection).MaxJsonLength;
return jsonResult;
Be sure you defined configuration element in web.config
If you use:
import Math
then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.
If you want to import a module's functions without having to prefix them, you must explicitly name them, like:
from Math import Calculate, Add, Subtract
Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:
from Math import *
However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.
Sort list of int descending you could just sort first and reverse
class Program
{
static void Main(string[] args)
{
List<int> myList = new List<int>();
myList.Add(38);
myList.Add(34);
myList.Add(35);
myList.Add(36);
myList.Add(37);
myList.Sort();
myList.Reverse();
myList.ForEach(Console.WriteLine);
}
}
If using mentioned jquery mousewheel plugin, then what about to use the 2nd argument of event handler function - delta
:
$('#my-element').on('mousewheel', function(event, delta) {
if(delta > 0) {
console.log('scroll up');
}
else {
console.log('scroll down');
}
});
date only work with GNU date (usually comes with Linux)
for OS X, two choices:
change command (verified)
#!/bin/sh #DATE=20090801204150 #date -jf "%Y%m%d%H%M%S" $DATE "+date \"%A,%_d %B %Y %H:%M:%S\"" date "Saturday, 1 August 2009 20:41:50"
http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html
Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html
You don't appear to understand what still reachable
means.
Anything still reachable
is not a leak. You don't need to do anything about it.
string ip = ((IPEndPoint)(testsocket.RemoteEndPoint)).Address.ToString();
All apps will continue to work in the vertically stretched screen from what I could tell in today's presentation. They will be letterboxed or basically the extra 88 points in height would simply be black.
If you only plan to support iOS 6+, then definitely consider using Auto Layout. It removes all fixed layout handling and instead uses constraints to lay things out. Nothing will be hard-coded, and your life will become a lot simpler.
However, if you have to support older iOS's, then it really depends on your application. A majority of applications that use a standard navigation bar, and/or tab bar, could simply expand the content in the middle to use up that extra points. Set the autoresizing mask of the center content to expand in both directions.
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
It works great out of the box for table views, however, if your app used pixel-perfect layout for displaying content, then your best bet would be to re-imagine the content so that it can accommodate varying heights.
If that's not a possibility, then the only remaining option is to have two UIs (pre iPhone 5, and iPhone 5).
If that sounds ugly, then you could go with the default letterboxed model where the extra points/pixels just show up black.
Edit
To enable your apps to work with iPhone 5, you need to add a retina version of the launcher image. It should be named [email protected]
. And it has to be retina quality - there's no backward compatibility here :)
You could also select this image from within Xcode. Go to the target, and under the Summary section, look for Launch Images. The image has to be 640x1136 pixels in size. Here's a screenshot of where to find it, if that helps.
If you are using the Android Support Library you can use ConfigurationCompat
instead of @Makalele's method to get rid of deprecation warnings:
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
or in Kotlin:
val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]
I know that this post is a bit old but incase anyone finds it still relevant you might want to check out the free geocoding services offered by USC College. This does included address validation via ajax and static calls. The only catch is that they request a link back and only offer allotments of 2500 calls. More than fair. https://webgis.usc.edu/Services/AddressValidation/Default.aspx
Hey there's a useful tutorial on Dot Net pearls: http://www.dotnetperls.com/progressbar
In agreement with Peter, you need to use some amount of threading or the program will just hang, somewhat defeating the purpose.
Example that uses ProgressBar and BackgroundWorker: C#
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Start the BackgroundWorker.
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
}
} //closing here
A faster, easier and more flexible way to do this is to use the strgen
module (pip install StringGenerator
).
Generate a 6-character random string with upper case letters and digits:
>>> from strgen import StringGenerator as SG
>>> SG("[\u\d]{6}").render()
u'YZI2CI'
Get a unique list:
>>> SG("[\l\d]{10}").render_list(5,unique=True)
[u'xqqtmi1pOk', u'zmkWdUr63O', u'PGaGcPHrX2', u'6RZiUbkk2i', u'j9eIeeWgEF']
Guarantee one "special" character in the string:
>>> SG("[\l\d]{10}&[\p]").render()
u'jaYI0bcPG*0'
A random HTML color:
>>> SG("#[\h]{6}").render()
u'#CEdFCa'
etc.
We need to be aware that this:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
might not have a digit (or uppercase character) in it.
strgen
is faster in developer-time than any of the above solutions. The solution from Ignacio is the fastest run-time performing and is the right answer using the Python Standard Library. But you will hardly ever use it in that form. You will want to use SystemRandom (or fallback if not available), make sure required character sets are represented, use unicode (or not), make sure successive invocations produce a unique string, use a subset of one of the string module character classes, etc. This all requires lots more code than in the answers provided. The various attempts to generalize a solution all have limitations that strgen solves with greater brevity and expressive power using a simple template language.
It's on PyPI:
pip install StringGenerator
Disclosure: I'm the author of the strgen module.
Here is My Code
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
if (gvDetail.Rows.Count > 0)
{
System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
gvDetail.RenderControl(htmlWrite1);
gvDetail.AllowPaging = false;
Search();
sh.ExportToExcel(gvDetail, "Report");
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
MsgBox("Variable {0} " , variable)
You need to iterate through all the enum values in Animal and return the value that matches the description you need.
Yes, that is supported.
Check the documentation provided here for the supported keywords inside method names.
You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:
List<Inventory> findByIdIn(List<Long> ids);
I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:
The Entity
@Entity
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
// other fields
// getters/setters
}
The Repository
@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {
List<Inventory> findByIdIn(List<Long> ids);
}
Easier solution;
#/bin/bash
if (( ${1:-2} >= 2 )); then
echo "First parameter must be 0 or 1"
fi
# rest of script...
Output
$ ./test
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1
Explanation
(( ))
- Evaluates the expression using integers.${1:-2}
- Uses parameter expansion to set a value of 2
if undefined.>= 2
- True if the integer is greater than or equal to two 2
.I think that you should try replacing php7.3-curl with api.hostip.info/?ip=$ip&position=true . Hope this helps
Comment from answer: "make sure you use the same open connection for all the database calls inside the transaction. – Magnus"
Our users are stored in a separate db from the data I was working with in the transactions. Opening the db connection to get the user was causing this error for me. Moving the other db connection and user lookup outside of the transaction scope fixed the error.
About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.
The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).
Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.
(Note that upgrading pip via pip install --upgrade pip
will also not upgrade it correctly. It is a chicken-and-egg issue)
This thread explains it (thanks to this Twitter post):
Mac users who use pip and PyPI:
If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:
curl https://bootstrap.pypa.io/get-pip.py | python
and we recommend you do that by April 8th.
Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/
Also, the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC
Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:
pip install --upgrade setuptools
Per JamieL's answer to another post:
Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.
Example:
res.json({"foo": "bar"});
You can try this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<layer-list>
<item android:left="1dp" android:top="3dp">
<shape>
<solid android:color="#a5040d" />
<corners android:radius="3dip"/>
</shape>
</item>
</layer-list>
</item>
<item>
<layer-list>
<item android:left="0dp" android:top="0dp">
<shape>
<solid android:color="#99080d" />
<corners android:radius="3dip"/>
</shape>
</item>
<item android:bottom="3dp" android:right="2dp">
<shape>
<solid android:color="#a5040d" />
<corners android:radius="3dip"/>
</shape>
</item>
</layer-list>
</item>
Today I learn some simple and good click event handling using tkinter gui library in python3, which I would like to share inside this thread.
from tkinter import *
cnt = 0
def MsgClick(event):
children = root.winfo_children()
for child in children:
# print("type of widget is : " + str(type(child)))
if str(type(child)) == "<class 'tkinter.Message'>":
# print("Here Message widget will destroy")
child.destroy()
return
def MsgMotion(event):
print("Mouse position: (%s %s)" % (event.x, event.y))
return
def ButtonClick(event):
global cnt, msg
cnt += 1
msg = Message(root, text="you just clicked the button..." + str(cnt) + "...time...")
msg.config(bg='lightgreen', font=('times', 24, 'italic'))
msg.bind("<Button-1>", MsgClick)
msg.bind("<Motion>", MsgMotion)
msg.pack()
#print(type(msg)) tkinter.Message
def ButtonDoubleClick(event):
import sys; sys.exit()
root = Tk()
root.title("My First GUI App in Python")
root.minsize(width=300, height=300)
root.maxsize(width=400, height=350)
button = Button(
root, text="Click Me!", width=40, height=3
)
button.pack()
button.bind("<Button-1>", ButtonClick)
button.bind("<Double-1>", ButtonDoubleClick)
root.mainloop()
Hope it will help someone...
if you don't export default in A, B, C but just export {} then it's possible to do so
// things/A.js
export function A() {}
// things/B.js
export function B() {}
// things/C.js
export function C() {}
// foo.js
import * as Foo from ./thing
Foo.A()
Foo.B()
Foo.C()
With the following code you can load the controller classes and execute the methods.
This code was written for codeigniter 2.1
First add a new file MY_Loader.php
in your application/core directory. Add the following code to your newly created MY_Loader.php
file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// written by AJ [email protected]
class MY_Loader extends CI_Loader
{
protected $_my_controller_paths = array();
protected $_my_controllers = array();
public function __construct()
{
parent::__construct();
$this->_my_controller_paths = array(APPPATH);
}
public function controller($controller, $name = '', $db_conn = FALSE)
{
if (is_array($controller))
{
foreach ($controller as $babe)
{
$this->controller($babe);
}
return;
}
if ($controller == '')
{
return;
}
$path = '';
// Is the controller in a sub-folder? If so, parse out the filename and path.
if (($last_slash = strrpos($controller, '/')) !== FALSE)
{
// The path is in front of the last slash
$path = substr($controller, 0, $last_slash + 1);
// And the controller name behind it
$controller = substr($controller, $last_slash + 1);
}
if ($name == '')
{
$name = $controller;
}
if (in_array($name, $this->_my_controllers, TRUE))
{
return;
}
$CI =& get_instance();
if (isset($CI->$name))
{
show_error('The controller name you are loading is the name of a resource that is already being used: '.$name);
}
$controller = strtolower($controller);
foreach ($this->_my_controller_paths as $mod_path)
{
if ( ! file_exists($mod_path.'controllers/'.$path.$controller.'.php'))
{
continue;
}
if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
{
if ($db_conn === TRUE)
{
$db_conn = '';
}
$CI->load->database($db_conn, FALSE, TRUE);
}
if ( ! class_exists('CI_Controller'))
{
load_class('Controller', 'core');
}
require_once($mod_path.'controllers/'.$path.$controller.'.php');
$controller = ucfirst($controller);
$CI->$name = new $controller();
$this->_my_controllers[] = $name;
return;
}
// couldn't find the controller
show_error('Unable to locate the controller you have specified: '.$controller);
}
}
Now you can load all the controllers in your application/controllers directory. for example:
load the controller class Invoice and execute the function test()
$this->load->controller('invoice','invoice_controller');
$this->invoice_controller->test();
or when the class is within a dir
$this->load->controller('/dir/invoice','invoice_controller');
$this->invoice_controller->test();
It just works the same like loading a model
The question has changed, so to has the answer:
Strings can't be tested using math.isnan
as this expects a float argument. In your countries
list, you have floats and strings.
In your case the following should suffice:
cleanedList = [x for x in countries if str(x) != 'nan']
In your countries
list, the literal 'nan'
is a string not the Python float nan
which is equivalent to:
float('NaN')
In your case the following should suffice:
cleanedList = [x for x in countries if x != 'nan']
You need to use <br>
instead of \r\n
. For this you can use built in function call nl2br
So your code should be like this
$message = nl2br("CCCC\r\nCCCC CCCC \r CCC \n CCC \r\n CCC \n\r CCCC");
there's also an interesting tool called CUFON. There's a demonstration of how to use it in this blog It's really simple and interesting. Also, it doesn't allow people to ctrl+c/ctrl+v the generated content.
On Mac OS
which virtualenvwrapper.sh
u got
/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh
and u can
sudo ln /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh /usr/local/bin/virtualenvwrapper.sh
and in your .bash_profile
source /usr/local/bin/virtualenvwrapper.sh
or u can
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh
While @jackofallcode answer is correct, it can be written in one line:
((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);
Using RxJs, you can declare a Subject
in your parent component and pass it as Observable
to child component, child component just need to subscribe to this Observable
.
Parent-Component
eventsSubject: Subject<void> = new Subject<void>();
emitEventToChild() {
this.eventsSubject.next();
}
Parent-HTML
<child [events]="eventsSubject.asObservable()"> </child>
Child-Component
private eventsSubscription: Subscription;
@Input() events: Observable<void>;
ngOnInit(){
this.eventsSubscription = this.events.subscribe(() => doSomething());
}
ngOnDestroy() {
this.eventsSubscription.unsubscribe();
}
Simply Enter Esc and type m it will convert to text cell.
If one or both of your dates are in the future, then I'm afraid you're SOL if you want to-the-second accuracy. UTC time has leap seconds that aren't known until about 6 months before they happen, so any dates further out than that can be inaccurate by some number of seconds (and in practice, since people don't update their machines that often, you may find that any time in the future is off by some number of seconds).
This gives a good explanation of the theory of designing date/time libraries and why this is so: http://www.boost.org/doc/libs/1_41_0/doc/html/date_time/details.html#date_time.tradeoffs
Lets say we have a variable called x, as below:
var x;
following statement is valid,
x = 10;
x = "a";
x = 0;
x = undefined;
x = null;
1. Number:
x = 10;
if(x){
//True
}
and for x = undefined
or x = 0
(be careful here)
if(x){
//False
}
2. String x = null
, x = undefined
or x = ""
if(x){
//False
}
3 Boolean x = false
and x = undefined
,
if(x){
//False
}
By keeping above in mind we can easily check, whether variable is empty, null, 0 or undefined in Angular js. Angular js doest provide separate API to check variable values emptiness.
SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');
The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like
SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');
where @h is the hour part of your string and @m is the minute part of your string
EDIT:
Here is a better way:
SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)
I had everything set up, but still couldn't see proper error pages for status code 500 on our staging server, despite the fact everything worked fine on local development servers.
I found this blog post from Rick Strahl that helped me.
I needed to add Response.TrySkipIisCustomErrors = true;
to my custom error handling code.
A simple code to list all the Items from DynamoDB Table by specifying the region of AWS Service.
import boto3
dynamodb = boto3.resource('dynamodb', region_name='ap-south-1')
table = dynamodb.Table('puppy_store')
response = table.scan()
items = response['Items']
# Prints All the Items at once
print(items)
# Prints Items line by line
for i, j in enumerate(items):
print(f"Num: {i} --> {j}")
I have also faced this issue. In my case, I allocated for x size memory and appended the data for x+n size. So, when freeing it shown heap overflow. Just make sure your allocated memory sufficient and check for how many bytes added in the memory.
Do not use global variables in this way. Even if this could work, it's bad programming style. You can inadvertently overwrite important data in this way. Do this instead:
<script type="text/javascript">
function kk(){
var lol = document.getElementById('lolz').value;
alert(lol);
}
</script>
If you insist var lol
to be set outside the function kk, then I propose this solution:
<body>
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" OnClick="kk()"/>
<script type="text/javascript">
var lol = document.getElementById('lolz');
function kk() {
alert(lol.value);
}
</script>
</body>
Note that the script
element must follow the input
element it refers to, because elements are only queryable with getElementById
if they already have been parsed and created.
Both examples work, tested in jsfiddler.
Edit: I removed the language="javascript"
attribute, because it's deprecated. See W3 HTML4 Specification, the SCRIPT element:
Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.
and
A deprecated element or attribute is one that has been outdated by newer constructs. […] Deprecated elements may become obsolete in future versions of HTML. […] This specification includes examples that illustrate how to avoid using deprecated elements. […]
if the device is locked with black screen run the following:
The connection string generated by the project containing the .edmx file generates the connection string, this would appear to be a holdover from the app.config sorts of files that were copied to the output directory and referenced by the executable to store runtime config information.
This breaks in the web project as there is no automatic process to add random .config information into the web.config file for the web project.
Easiest is to copy the connection string from the config file to the connections section of the web.config file and disregard the config file contents.
I have also used a non-generic version, using the new
keyword:
public interface IMetadata
{
Type DataType { get; }
object Data { get; }
}
public interface IMetadata<TData> : IMetadata
{
new TData Data { get; }
}
Explicit interface implementation is used to allow both Data
members:
public class Metadata<TData> : IMetadata<TData>
{
public Metadata(TData data)
{
Data = data;
}
public Type DataType
{
get { return typeof(TData); }
}
object IMetadata.Data
{
get { return Data; }
}
public TData Data { get; private set; }
}
You could derive a version targeting value types:
public interface IValueTypeMetadata : IMetadata
{
}
public interface IValueTypeMetadata<TData> : IMetadata<TData>, IValueTypeMetadata where TData : struct
{
}
public class ValueTypeMetadata<TData> : Metadata<TData>, IValueTypeMetadata<TData> where TData : struct
{
public ValueTypeMetadata(TData data) : base(data)
{}
}
This can be extended to any kind of generic constraints.
One way I like to use is:
select ,COUNT()as VAR1 from Table_Name
group by
order by VAR1 desc
limit 1
I think you will need to do this as three separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.
ALTER TABLE dbo.MyTable
ADD CONSTRAINT my_Con DEFAULT GETDATE() for created
UPDATE MyTable SET Created = GetDate() where Created IS NULL
ALTER TABLE dbo.MyTable
ALTER COLUMN Created DATETIME NOT NULL
You haven't specified what the query should return if more than one document is added at the same time, so this query assumes you want all of them returned:
SELECT t.ID,
t.USER_ID,
t.DATE_ADDED,
t.DATE_VIEWED,
t.DOCUMENT_ID,
t.URL,
t.DOCUMENT_TITLE,
t.DOCUMENT_DATE
FROM (
SELECT test_table.*,
RANK()
OVER (ORDER BY DOCUMENT_DATE DESC) AS the_rank
FROM test_table
WHERE user_id = value
)
WHERE the_rank = 1;
This query will only make one pass through the data.
If you mean delete every instance of all models, I would use
ActiveRecord::Base.connection.tables.map(&:classify)
.map{|name| name.constantize if Object.const_defined?(name)}
.compact.each(&:delete_all)
The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:
import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square')
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(xi, x)
plt.title('compare')
plt.legend()
plt.show()
They are identical: BETWEEN
is a shorthand for the longer syntax in the question.
Use an alternative longer syntax where BETWEEN
doesn't work e.g.
Select EventId,EventName from EventMaster
where EventDate >= '10/15/2009' and EventDate < '10/19/2009'
(Note <
rather than <=
in second condition.)
The best answer I can find, is in one of the comments here. Adding it to the answer so that someone won't miss the comment and should definitely try this out. It fixed the issue for me.
We need to map the solution folder to a drive using the "subst" command in command prompt- e.g., subst z:
And then open the solution from this drive (z in this case). This would shorten the path as much as possible and could solve the lengthy filename issue.
That is not possible with a normal query since the in
clause needs separate values and not a single value containing a comma separated list. One solution would be a dynamic query
declare @myList varchar(100)
set @myList = '(1,2,5,7,10)'
exec('select * from DBTable where id IN ' + @myList)
Perhaps you're not disposing of the previous connection/ result classes from the previous run which means their still hanging around in memory.
Here is the complete answer to the question.
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
class ListIterator implements Iterator<String>{
List<String> list;
int pos = 0;
public ListIterator(List<String> list) {
this.list = list;
}
@Override
public boolean hasNext() {
while(pos < list.size()){
if (list.get(pos).startsWith("a"))
return true;
pos++;
}
return false;
}
@Override
public String next() {
if (hasNext())
return list.get(pos++);
throw new NoSuchElementException();
}
}
public class IteratorTest {
public static void main(String[] args) {
List<String> list = Arrays.asList("alice", "bob", "abigail", "charlie");
ListIterator itr = new ListIterator(list);
while(itr.hasNext())
System.out.println(itr.next()); // prints alice, abigail
}
}
ListIterator
is the iterator for the array which returns the elements that start with 'a'. NoSuchElementException
exception.The query below will give you a list of all users and their permissions on the table in a schema.
select a.schemaname, a.tablename, b.usename,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'select') as has_select,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'insert') as has_insert,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'update') as has_update,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'delete') as has_delete,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'references') as has_references
from pg_tables a, pg_user b
where a.schemaname = 'your_schema_name' and a.tablename='your_table_name';
More details on has_table_privilages
can be found here.
Try:
g = pd.DataFrame(['A','B','A','C','D','D','E'])
# Group by the contents of column 0
gg = g.groupby(0)
# Create a DataFrame with the counts of each letter
histo = gg.apply(lambda x: x.count())
# Add a new column that is the count / total number of elements
histo[1] = histo.astype(np.float)/len(g)
print histo
Output:
0 1
0
A 2 0.285714
B 1 0.142857
C 1 0.142857
D 2 0.285714
E 1 0.142857
This is a lot larger, but I think it looks a little more comprehensive: http://www.obviex.com/Samples/Password.aspx
///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Generates random password, which complies with the strong password
// rules and does not contain ambiguous characters.
//
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Copyright (C) 2004 Obviex(TM). All rights reserved.
//
using System;
using System.Security.Cryptography;
/// <summary>
/// This class can generate random passwords, which do not include ambiguous
/// characters, such as I, l, and 1. The generated password will be made of
/// 7-bit ASCII symbols. Every four characters will include one lower case
/// character, one upper case character, one number, and one special symbol
/// (such as '%') in a random order. The password will always start with an
/// alpha-numeric character; it will not start with a special symbol (we do
/// this because some back-end systems do not like certain special
/// characters in the first position).
/// </summary>
public class RandomPassword
{
// Define default min and max password lengths.
private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;
private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;
// Define supported password characters divided into groups.
// You can add (or remove) characters to (from) these groups.
private static string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
private static string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";
private static string PASSWORD_CHARS_NUMERIC= "23456789";
private static string PASSWORD_CHARS_SPECIAL= "*$-+?_&=!%{}/";
/// <summary>
/// Generates a random password.
/// </summary>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random. It will be no shorter than the minimum default and
/// no longer than maximum default.
/// </remarks>
public static string Generate()
{
return Generate(DEFAULT_MIN_PASSWORD_LENGTH,
DEFAULT_MAX_PASSWORD_LENGTH);
}
/// <summary>
/// Generates a random password of the exact length.
/// </summary>
/// <param name="length">
/// Exact password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
public static string Generate(int length)
{
return Generate(length, length);
}
/// <summary>
/// Generates a random password.
/// </summary>
/// <param name="minLength">
/// Minimum password length.
/// </param>
/// <param name="maxLength">
/// Maximum password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random and it will fall with the range determined by the
/// function parameters.
/// </remarks>
public static string Generate(int minLength,
int maxLength)
{
// Make sure that input parameters are valid.
if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
return null;
// Create a local array containing supported password characters
// grouped by types. You can remove character groups from this
// array, but doing so will weaken the password strength.
char[][] charGroups = new char[][]
{
PASSWORD_CHARS_LCASE.ToCharArray(),
PASSWORD_CHARS_UCASE.ToCharArray(),
PASSWORD_CHARS_NUMERIC.ToCharArray(),
PASSWORD_CHARS_SPECIAL.ToCharArray()
};
// Use this array to track the number of unused characters in each
// character group.
int[] charsLeftInGroup = new int[charGroups.Length];
// Initially, all characters in each group are not used.
for (int i=0; i<charsLeftInGroup.Length; i++)
charsLeftInGroup[i] = charGroups[i].Length;
// Use this array to track (iterate through) unused character groups.
int[] leftGroupsOrder = new int[charGroups.Length];
// Initially, all character groups are not used.
for (int i=0; i<leftGroupsOrder.Length; i++)
leftGroupsOrder[i] = i;
// Because we cannot use the default randomizer, which is based on the
// current time (it will produce the same "random" number within a
// second), we will use a random number generator to seed the
// randomizer.
// Use a 4-byte array to fill it with random bytes and convert it then
// to an integer value.
byte[] randomBytes = new byte[4];
// Generate 4 random bytes.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert 4 bytes into a 32-bit integer value.
int seed = BitConverter.ToInt32(randomBytes, 0);
// Now, this is real randomization.
Random random = new Random(seed);
// This array will hold password characters.
char[] password = null;
// Allocate appropriate memory for the password.
if (minLength < maxLength)
password = new char[random.Next(minLength, maxLength+1)];
else
password = new char[minLength];
// Index of the next character to be added to password.
int nextCharIdx;
// Index of the next character group to be processed.
int nextGroupIdx;
// Index which will be used to track not processed character groups.
int nextLeftGroupsOrderIdx;
// Index of the last non-processed character in a group.
int lastCharIdx;
// Index of the last non-processed group.
int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// Generate password characters one at a time.
for (int i=0; i<password.Length; i++)
{
// If only one character group remained unprocessed, process it;
// otherwise, pick a random character group from the unprocessed
// group list. To allow a special character to appear in the
// first position, increment the second parameter of the Next
// function call by one, i.e. lastLeftGroupsOrderIdx + 1.
if (lastLeftGroupsOrderIdx == 0)
nextLeftGroupsOrderIdx = 0;
else
nextLeftGroupsOrderIdx = random.Next(0,
lastLeftGroupsOrderIdx);
// Get the actual index of the character group, from which we will
// pick the next character.
nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
// Get the index of the last unprocessed characters in this group.
lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
// If only one unprocessed character is left, pick it; otherwise,
// get a random character from the unused character list.
if (lastCharIdx == 0)
nextCharIdx = 0;
else
nextCharIdx = random.Next(0, lastCharIdx+1);
// Add this character to the password.
password[i] = charGroups[nextGroupIdx][nextCharIdx];
// If we processed the last character in this group, start over.
if (lastCharIdx == 0)
charsLeftInGroup[nextGroupIdx] =
charGroups[nextGroupIdx].Length;
// There are more unprocessed characters left.
else
{
// Swap processed character with the last unprocessed character
// so that we don't pick it until we process all characters in
// this group.
if (lastCharIdx != nextCharIdx)
{
char temp = charGroups[nextGroupIdx][lastCharIdx];
charGroups[nextGroupIdx][lastCharIdx] =
charGroups[nextGroupIdx][nextCharIdx];
charGroups[nextGroupIdx][nextCharIdx] = temp;
}
// Decrement the number of unprocessed characters in
// this group.
charsLeftInGroup[nextGroupIdx]--;
}
// If we processed the last group, start all over.
if (lastLeftGroupsOrderIdx == 0)
lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// There are more unprocessed groups left.
else
{
// Swap processed group with the last unprocessed group
// so that we don't pick it until we process all groups.
if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
{
int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
leftGroupsOrder[lastLeftGroupsOrderIdx] =
leftGroupsOrder[nextLeftGroupsOrderIdx];
leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
}
// Decrement the number of unprocessed groups.
lastLeftGroupsOrderIdx--;
}
}
// Convert password characters into a string and return the result.
return new string(password);
}
}
/// <summary>
/// Illustrates the use of the RandomPassword class.
/// </summary>
public class RandomPasswordTest
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
// Print 100 randomly generated passwords (8-to-10 char long).
for (int i=0; i<100; i++)
Console.WriteLine(RandomPassword.Generate(8, 10));
}
}
//
// END OF FILE
///////////////////////////////////////////////////////////////////////////////
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where
strm
is the identifier of a istream object andvariable
is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object
strm
.
Just replace strm
with cin
.
You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':
len(data['result'][0]['run'])
public function randomString($length = 8)
{
$characters = implode([
'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',
'abcdefghijklmnoprqstuwvxyz',
'0123456789',
//'!@#$%^&*?'
]);
$charactersLength = strlen($characters) - 1;
$string = '';
while ($length) {
$string .= $characters[mt_rand(0, $charactersLength)];
--$length;
}
return $string;
}
This solution works with Swift 4 (Xcode 9.2) and also with Swift 5 (Xcode 10.2.1+):
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
// process files
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}
Here's a reusable FileManager extension that also lets you skip or include hidden files in the results:
import Foundation
extension FileManager {
func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
let documentsURL = urls(for: directory, in: .userDomainMask)[0]
let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
return fileURLs
}
}
// Usage
print(FileManager.default.urls(for: .documentDirectory) ?? "none")
If you don't have access to sysjobs table (someone elses server etc) you might be have or be allowed access to sysjobs_view
SELECT *
from msdb..sysjobs_view s
left join master.sys.syslogins l on s.owner_sid = l.sid
or
SELECT *, SUSER_SNAME(s.owner_sid) AS owner
from msdb..sysjobs_view s
I had this issue because the tutorial code I was trying to run wasn't in the correct package even though I had typed in the package name at the top of each class.
I right-clicked each class, Refactor
and Move To
and accepted the package name suggestion.
Then as usual, Run As
... Java Application
.
And it worked :)
If you need to compare only day of month value than you can use the following code:
if yourdate.day == datetime.today().day:
# do something
If you need to check that the difference between two dates is acceptable then you can use timedelta:
if (datetime.today() - yourdate).days == 0:
#do something
And if you want to compare date part only than you can simply use:
from datetime import datetime, date
if yourdatetime.date() < datetime.today().date()
# do something
Note that timedelta has the following format:
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
So you are able to check diff in days, seconds, msec, minutes and so on depending on what you really need:
from datetime import datetime
if (datetime.today() - yourdate).days == 0:
#do something
In your case when you need to check that two dates are exactly the same you can use timedelta(0):
from datetime import datetime, timedelta
if (datetime.today() - yourdate) == timedelta(0):
#do something
This can be done using ServerSocket, same as on JavaSE. This class is available on Android. android.permission.INTERNET
is required.
The only more tricky part, you need a separate thread wait on the ServerSocket, servicing sub-sockets that come from its accept
method. You also need to stop and resume this thread as needed. The simplest approach seems to kill the waiting thread by closing the ServerSocket.
If you only need a server while your activity is on the top, starting and stopping ServerSocket thread can be rather elegantly tied to the activity life cycle methods. Also, if the server has multiple users, it may be good to service requests in the forked threads. If there is only one user, this may not be necessary.
If you need to tell the user on which IP is the server listening,use NetworkInterface.getNetworkInterfaces(), this question may tell extra tricks.
Finally, here there is possibly the complete minimal Android server that is very short, simple and may be easier to understand than finished end user applications, recommended in other answers.
In the initialization chunk I define a function
pagebreak <- function() {
if(knitr::is_latex_output())
return("\\newpage")
else
return('<div style="page-break-before: always;" />')
}
In the markdown part where I want to insert a page break, I type
`r pagebreak()`
Have your tried using the 'return' keyword?
def rps():
return True
same for Terminator
Ctrl + Shift + V
Look at your terminal key-bindings if any if that doesn't work
Using d-flex
class works well but some other attributes don't work anymore like vertical-align: middle
property.
The best way I found to size columns very easily is to use the width
attribute with percentage only in thead
cells.
<table class="table">
<thead>
<tr>
<th width="25%">25%</th>
<th width="25%">25%</th>
<th width="50%">50%</th>
</tr>
</thead>
<tbody>
<tr>
<td>25%</td>
<td>25%</td>
<td>50%</td>
</tr>
</tbody>
</table>
If your modulus / divisor is a known constant, and you care about performance, see this and this. A multiplicative inverse is even possible for loop-invariant values that aren't known until runtime, e.g. see https://libdivide.com/ (But without JIT code-gen, that's less efficient than hard-coding just the steps necessary for one constant.)
Never use div
for known powers of 2: it's much slower than and
for remainder, or right-shift for divide. Look at C compiler output for examples of unsigned or signed division by powers of 2, e.g. on the Godbolt compiler explorer. If you know a runtime input is a power of 2, use lea eax, [esi-1]
; and eax, edi
or something like that to do x & (y-1)
. Modulo 256 is even more efficient: movzx eax, cl
has zero latency on recent Intel CPUs (mov-elimination), as long as the two registers are separate.
The DIV
instruction (and its counterpart IDIV
for signed numbers) gives both the quotient and remainder. For unsigned, remainder and modulus are the same thing. For signed idiv
, it gives you the remainder (not modulus) which can be negative:
e.g. -5 / 2 = -2 rem -1
. x86 division semantics exactly match C99's %
operator.
DIV r32
divides a 64-bit number in EDX:EAX
by a 32-bit operand (in any register or memory) and stores the quotient in EAX
and the remainder in EDX
. It faults on overflow of the quotient.
Unsigned 32-bit example (works in any mode)
mov eax, 1234 ; dividend low half
mov edx, 0 ; dividend high half = 0. prefer xor edx,edx
mov ebx, 10 ; divisor can be any register or memory
div ebx ; Divides 1234 by 10.
; EDX = 4 = 1234 % 10 remainder
; EAX = 123 = 1234 / 10 quotient
In 16-bit assembly you can do div bx
to divide a 32-bit operand in DX:AX
by BX
. See Intel's Architectures Software Developer’s Manuals for more information.
Normally always use xor edx,edx
before unsigned div
to zero-extend EAX into EDX:EAX. This is how you do "normal" 32-bit / 32-bit => 32-bit division.
For signed division, use cdq
before idiv
to sign-extend EAX into EDX:EAX. See also Why should EDX be 0 before using the DIV instruction?. For other operand-sizes, use cbw
(AL->AX), cwd
(AX->DX:AX), cdq
(EAX->EDX:EAX), or cqo
(RAX->RDX:RAX) to set the top half to 0
or -1
according to the sign bit of the low half.
div
/ idiv
are available in operand-sizes of 8, 16, 32, and (in 64-bit mode) 64-bit. 64-bit operand-size is much slower than 32-bit or smaller on current Intel CPUs, but AMD CPUs only care about the actual magnitude of the numbers, regardless of operand-size.
Note that 8-bit operand-size is special: the implicit inputs/outputs are in AH:AL (aka AX), not DL:AL. See 8086 assembly on DOSBox: Bug with idiv instruction? for an example.
Signed 64-bit division example (requires 64-bit mode)
mov rax, 0x8000000000000000 ; INT64_MIN = -9223372036854775808
mov ecx, 10 ; implicit zero-extension is fine for positive numbers
cqo ; sign-extend into RDX, in this case = -1 = 0xFF...FF
idiv rcx
; quotient = RAX = -922337203685477580 = 0xf333333333333334
; remainder = RDX = -8 = 0xfffffffffffffff8
div dword 10
is not encodeable into machine code (so your assembler will report an error about invalid operands).
Unlike with mul
/imul
(where you should normally use faster 2-operand imul r32, r/m32
or 3-operand imul r32, r/m32, imm8/32
instead that don't waste time writing a high-half result), there is no newer opcode for division by an immediate, or 32-bit/32-bit => 32-bit division or remainder without the high-half dividend input.
Division is so slow and (hopefully) rare that they didn't bother to add a way to let you avoid EAX and EDX, or to use an immediate directly.
div and idiv will fault if the quotient doesn't fit into one register (AL / AX / EAX / RAX, the same width as the dividend). This includes division by zero, but will also happen with a non-zero EDX and a smaller divisor. This is why C compilers just zero-extend or sign-extend instead of splitting up a 32-bit value into DX:AX.
And also why INT_MIN / -1
is C undefined behaviour: it overflows the signed quotient on 2's complement systems like x86. See Why does integer division by -1 (negative one) result in FPE? for an example of x86 vs. ARM. x86 idiv
does indeed fault in this case.
The x86 exception is #DE
- divide exception. On Unix/Linux systems, the kernel delivers a SIGFPE arithmetic exception signal to processes that cause a #DE exception. (On which platforms does integer divide by zero trigger a floating point exception?)
For div
, using a dividend with high_half < divisor
is safe. e.g. 0x11:23 / 0x12
is less than 0xff
so it fits in an 8-bit quotient.
Extended-precision division of a huge number by a small number can be implemented by using the remainder from one chunk as the high-half dividend (EDX) for the next chunk. This is probably why they chose remainder=EDX quotient=EAX instead of the other way around.
You technically have two options when speaking of ISO dates.
In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd
or y-m-d
. Which are both valid ISO formats.
Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.
Because of this, your safest bet is to persist/filter based on the always netural ymd
format.
The code:
select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)
To avoid confusion (as there seems to be some in the comments). Assuming you are on Jupyter:
%matplotlib inline
> displays the plots INSIDE the notebook
sns.plt.show()
> displays the plots OUTSIDE of the notebook
%matplotlib inline
will OVERRIDE sns.plt.show()
in the sense that plots will be shown IN the notebook even when sns.plt.show()
is called.
And yes, it is easy to include the line in to your config:
Automatically run %matplotlib inline in IPython Notebook
But it seems a better convention to keep it together with imports in the actual code.
Say you have a container with two divs inside and you want those two divs to have the same height.
You would set 'display: flex' on the container as well as 'align-items: stretch'
Then just give the child divs a 'min-height' of 100%
See the code below
.container {
width: 100%;
background: linear-gradient(red,blue);
padding: 1em;
/* important */
display: flex;
/* important */
align-items: stretch;
justify-content: space-around;
}
.child {
width: 100%;
background: white;
color: grey;
margin: 0 .5em;
padding: .5em;
/* important */
min-height: 100%;
}
_x000D_
<div class="container">
<div class="child"><p>This is some text to fill the paragraph</p></div>
<div class="child"><p>This is a lot of text to show you that the other div will stretch to the same height as this one even though they do not have the same amount of text inside them. If you remove text from this div, it will shrink and so will the other div.</p></div>
</div>
_x000D_
Enable "resolveJsonModule": true
in tsconfig.json
file and implement as below code, it's work for me:
const config = require('./config.json');
This is a very common case in DataTables when it's not able to find the request field define in DataTable configuration.
For Example:
"aoColumns": [{
mData: 'mobile', sWidth: "149px;"
}, {
mData: 'name', sWidth: "121px;"
}, {
mData: 'productName', sWidth: "116px;"
}
}];
Here, If DataTable doesn't receive above mentioned properties. It'll generate this warning:
DataTables warning: Requested unknown parameter '0' from the data source for row '0'
To overcome this you just need to simply set a default value in "aoColumns"
For Example:
"aoColumns": [{
mData: 'mobile',sDefaultContent : '',sWidth: "149px;"
}, {
mData: 'name',sDefaultContent : '', sWidth: "121px;"
}, {
mData: 'productName',sDefaultContent : '', sWidth: "116px;"
}
}];
sDefaultContent will supress the warning.
Note: This property could be changed based on version of dataTables you are using.
Raymond Chen gives a nice overview of what __stdcall
and __cdecl
does.
(1) The caller "knows" to clean up the stack after calling a function because the compiler knows the calling convention of that function and generates the necessary code.
void __stdcall StdcallFunc() {}
void __cdecl CdeclFunc()
{
// The compiler knows that StdcallFunc() uses the __stdcall
// convention at this point, so it generates the proper binary
// for stack cleanup.
StdcallFunc();
}
It is possible to mismatch the calling convention, like this:
LRESULT MyWndProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam);
// ...
// Compiler usually complains but there's this cast here...
windowClass.lpfnWndProc = reinterpret_cast<WNDPROC>(&MyWndProc);
So many code samples get this wrong it's not even funny. It's supposed to be like this:
// CALLBACK is #define'd as __stdcall
LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg
WPARAM wParam, LPARAM lParam);
// ...
windowClass.lpfnWndProc = &MyWndProc;
However, assuming the programmer doesn't ignore compiler errors, the compiler will generate the code needed to clean up the stack properly since it'll know the calling conventions of the functions involved.
(2) Both ways should work. In fact, this happens quite frequently at least in code that interacts with the Windows API, because __cdecl
is the default for C and C++ programs according to the Visual C++ compiler and the WinAPI functions use the __stdcall
convention.
(3) There should be no real performance difference between the two.
Use sudo npm install -g appium
.
This actually is possible, and I discovered how quite by accident while designing my first large-scale responsive design site.
<div class="wrapper">
<div class="box">
<img src="/logo.png" alt="">
</div>
</div>
.wrapper { position:relative; overflow:hidden; }
.box { float:left; } //Note: 'float:right' would work too
.box > img { width:50%; }
The overflow:hidden gives the wrapper height and width, despite the floating contents, without using the clearfix hack. You can then position your content using margins. You can even make the wrapper div an inline-block.
I had a similar problem.
Error response from daemon: Get https://registry-1.docker.io/v2/hadolint/hadolint/manifests/latest: unauthorized: incorrect username or password
I found out out that even if I login successfully with the docker login
command, any pull failed.
I tried to clean up the ~/.docker/config.json
but nothing improved.
Looking in the config file I've seen that the credentials were not saved there but in a "credsStore": "secretservice"
.
In Linux this happen to be the seahorse
or Passwords and Keys
tool.
I checked there and I cleanup all the docker hub login.
After this a new docker login worked as expected.
First try to open the file with a decompiler such as ILSpy, your dll might be corrupt. I had this error on an online web site, when I downloaded the dll and tried to open it, it was corrupt, probably some error occurred while uploading it via ftp.
Popen expect a list of strings for non-shell calls and a string for shell calls.
Call subprocess.Popen with shell=True:
process = subprocess.Popen(command, stdout=tempFile, shell=True)
Hopefully this solves your issue.
This issue is listed here: https://bugs.python.org/issue17023
To check if a folder exists or not, you can simply use the exists()
method:
// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )
// If it doesn't exist
if( !folder.exists() ) {
// Create all folders up-to and including B
folder.mkdirs()
}
// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
w << "Some text\n"
}
get_or_create()
returns a tuple:
customer.source, created = Source.objects.get_or_create(name="Website")
created
? has a boolean value, is created or not.
customer.source
? has an object of get_or_create()
method.
I just planned to share some knowledge.
Deadlocks A set of threads/processes is deadlocked, if each thread/process in the set is waiting for an event that only another process in the set can cause.
The important thing here is another process is also in the same set. that means another process also blocked and no one can proceed.
Deadlocks occur when processes are granted exclusive access to resources.
These four conditions should be satisfied to have a deadlock.
If we found these conditions then we can say there may be occurred a situation like a deadlock.
LiveLock
Each thread/process is repeating the same state again and again but doesn't progress further. Something similar to a deadlock since the process can not enter the critical section. However in a deadlock, processes are wait without doing anything but in livelock, the processes are trying to proceed but processes are repeated to the same state again and again.
(In a deadlocked computation there is no possible execution sequence which succeeds. but In a livelocked computation, there are successful computations, but there are one or more execution sequences in which no process enters its critical section.)
Difference from deadlock and livelock
When deadlock happens, No execution will happen. but in livelock, some executions will happen but those executions are not enough to enter the critical section.
A longer one that counts inversions and adheres to the sorted
interface. It's trivial to modify this to make it a method of an object that sorts in place.
import operator
class MergeSorted:
def __init__(self):
self.inversions = 0
def __call__(self, l, key=None, reverse=False):
self.inversions = 0
if key is None:
self.key = lambda x: x
else:
self.key = key
if reverse:
self.compare = operator.gt
else:
self.compare = operator.lt
dest = list(l)
working = [0] * len(l)
self.inversions = self._merge_sort(dest, working, 0, len(dest))
return dest
def _merge_sort(self, dest, working, low, high):
if low < high - 1:
mid = (low + high) // 2
x = self._merge_sort(dest, working, low, mid)
y = self._merge_sort(dest, working, mid, high)
z = self._merge(dest, working, low, mid, high)
return (x + y + z)
else:
return 0
def _merge(self, dest, working, low, mid, high):
i = 0
j = 0
inversions = 0
while (low + i < mid) and (mid + j < high):
if self.compare(self.key(dest[low + i]), self.key(dest[mid + j])):
working[low + i + j] = dest[low + i]
i += 1
else:
working[low + i + j] = dest[mid + j]
inversions += (mid - (low + i))
j += 1
while low + i < mid:
working[low + i + j] = dest[low + i]
i += 1
while mid + j < high:
working[low + i + j] = dest[mid + j]
j += 1
for k in range(low, high):
dest[k] = working[k]
return inversions
msorted = MergeSorted()
Uses
>>> l = [5, 2, 3, 1, 4]
>>> s = msorted(l)
>>> s
[1, 2, 3, 4, 5]
>>> msorted.inversions
6
>>> l = ['e', 'b', 'c', 'a', 'd']
>>> d = {'a': 10,
... 'b': 4,
... 'c': 2,
... 'd': 5,
... 'e': 9}
>>> key = lambda x: d[x]
>>> s = msorted(l, key=key)
>>> s
['c', 'b', 'd', 'e', 'a']
>>> msorted.inversions
5
>>> l = [5, 2, 3, 1, 4]
>>> s = msorted(l, reverse=True)
>>> s
[5, 4, 3, 2, 1]
>>> msorted.inversions
4
>>> l = ['e', 'b', 'c', 'a', 'd']
>>> d = {'a': 10,
... 'b': 4,
... 'c': 2,
... 'd': 5,
... 'e': 9}
>>> key = lambda x: d[x]
>>> s = msorted(l, key=key, reverse=True)
>>> s
['a', 'e', 'd', 'b', 'c']
>>> msorted.inversions
5
foreach my $key (keys %$ad_grp_ref) {
...
}
Perl::Critic
and daxim recommend the style
foreach my $key (keys %{ $ad_grp_ref }) {
...
}
out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() }
instead of %{ $ad_grp_ref }
)
In the manifest file, under the tag, there will be a similar line:
android:icon="drawable_resource_path"
Place the launcher icon you want in drawable folder and write its resource path.
For properties configuration
# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties)
endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.
even i'm working on same kind of project [An Onlinw Word Processor]! But i've choosen c#.net and ASP.net. But through the survey i did; i got to know that
By Using Open XML SDK and VSTO [Visual Studio Tools For Office]
we may easily work with a word file manipulate them and even convert internally to different into several formats such as .odt,.pdf,.docx etc..
So, goto msdn.microsoft.com and be thorough about the office development tab. Its the easiest way to do this as all functions we need to implement are already available in .net!!
But as u want to do ur project in PHP, u can do it in Visual Studio and .net as PHP is also one of the .net Compliant Language!!
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
The job of interpreting the pipe symbol as an instruction to run multiple processes and pipe the output of one process into the input of another process is the responsibility of the shell (/bin/sh or equivalent).
In your example you can either choose to use your top level shell to perform the piping like so:
find -name 'file_*' -follow -type f -exec zcat {} \; | agrep -dEOE 'grep'
In terms of efficiency this results costs one invocation of find, numerous invocations of zcat, and one invocation of agrep.
This would result in only a single agrep process being spawned which would process all the output produced by numerous invocations of zcat.
If you for some reason would like to invoke agrep multiple times, you can do:
find . -name 'file_*' -follow -type f \
-printf "zcat %p | agrep -dEOE 'grep'\n" | sh
This constructs a list of commands using pipes to execute, then sends these to a new shell to actually be executed. (Omitting the final "| sh" is a nice way to debug or perform dry runs of command lines like this.)
In terms of efficiency this results costs one invocation of find, one invocation of sh, numerous invocations of zcat and numerous invocations of agrep.
The most efficient solution in terms of number of command invocations is the suggestion from Paul Tomblin:
find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'
... which costs one invocation of find, one invocation of xargs, a few invocations of zcat and one invocation of agrep.
I would use
print(String(format: "%.3f", totalWorkTimeInHours))
and change .3f to any number of decimal numbers you need
If you have 2 installations of the JVM. Place the version upfront. Linux : export PATH=/usr/lib/jvm/java-8-oracle/bin:$PATH
This eliminates the ambiguity.
v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.
So, you should override it with display: flex
in your HTML or CSS to make it work with justify-content.
WE had this issue. everything was setup fine in terms of permissions and security.
after MUCH needling around in the haystack. the issue was some sort of heuristics. in the email body , anytime a certain email address was listed, we would get the above error message from our exchange server.
it took 2 days of crazy testing and hair pulling to find this.
so if you have checked everything out, try changing the email body to only the word 'test'. If after that, your email goes out fine, you are having some sort of spam/heuristic filter issue like we were
Magic word is: isset
Validate the entry:
if(isset($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
I know this is an old post and I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.
I wish this were just part of the base Dictionary class.
public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
TValue _default;
public TValue DefaultValue {
get { return _default; }
set { _default = value; }
}
public DictionaryWithDefault() : base() { }
public DictionaryWithDefault(TValue defaultValue) : base() {
_default = defaultValue;
}
public new TValue this[TKey key]
{
get {
TValue t;
return base.TryGetValue(key, out t) ? t : _default;
}
set { base[key] = value; }
}
}
Beware, however. By subclassing and using new
(since override
is not available on the native Dictionary
type), if a DictionaryWithDefault
object is upcast to a plain Dictionary
, calling the indexer will use the base Dictionary
implementation (throwing an exception if missing) rather than the subclass's implementation.
class Foo (object):
# ^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
#^ double underscore (dunder) methods are usually special. This one
# gets called immediately after a new instance is created.
self.variable = "Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self, arg1, arg2):
#This method has arguments. You would call it like this: instance.method(1, 2)
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo
There's a huge difference. As has been mentioned, <%@ include
is a static include, <jsp:include
is a dynamic include. Think of it as a difference between a macro and a function call (if you are familiar with those terms). Another way of putting it, a static include is exactly the same thing as copy-pasting the exact content of the included file (the "code") at the location of the <%@ include
statement (which is exactly what the JSP compiler will do.
A dynamic include will make a request (using the request dispatcher) that will execute the indicated page and then include the output from the page in the output of the calling page, in place of the <jsp:include
statement.
The big difference here is that with a dynamic include, the included page will execute in it's own pageContext. And since it's a request, you can send parameters to the page the same way you can send parameters along with any other request. A static include, on the other hand, is just a piece of code that will execute inside the context of the calling page. If you statically include the same file more than once, the code in that file will exist in multiple locations on the calling page so something like
<%
int i = 0;
%>
would generate a compiler error (since the same variable can't be declared more than once).
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
I don't know if there's any solution to do this in a database-agnostic way, since you most likely will need some form of string manipulation, and those are typically different between vendors.
For SQL Server 2005 and up, you could use:
SELECT
r.ID, r.Name,
Resources = STUFF(
(SELECT ','+a.Name
FROM dbo.Applications a
INNER JOIN dbo.ApplicationsResources ar ON ar.app_id = a.id
WHERE ar.resource_id = r.id
FOR XML PATH('')), 1, 1, '')
FROM
dbo.Resources r
It uses the SQL Server 2005 FOR XML PATH
construct to list the subitems (the applications for a given resource) as a comma-separated list.
Marc
const str = "dGhpcyBpcyBiYXNlNjQgc3RyaW5n"
const encoded = new TextEncoder().encode(str) // is Uint8Array
const buf = encoded.buffer // is ArrayBuffer
In the Properties,
Go to Configuration Properties. In that go to C/C++ (or something like that). ,Then click General ,In that remove the check in the "Treat Warning As Errors" Check Box
I had the exact same error but with slightly different format and root-cause, and since this is the first Q&A that pops up when you search for "time data does not match format", I thought I'd leave the mistake I made for future viewers:
My initial code:
start = datetime.strptime('05-SEP-19 00.00.00.000 AM', '%d-%b-%y %I.%M.%S.%f %p')
Where I used %I
to parse the hours and %p
to parse 'AM/PM'.
The error:
ValueError: time data '05-SEP-19 00.00.00.000000 AM' does not match format '%d-%b-%y %I.%M.%S.%f %p'
I was going through the datetime docs and finally realized in 12-hour format %I
, there is no 00... once I changed 00.00.00
to 12.00.00
, the problem was resolved.
So it's either 01-12 using %I
with %p
, or 00-23 using %H
.
This checks the type of input arguments upon calling the function:
def func(inp1:int=0,inp2:str="*"):
for item in func.__annotations__.keys():
assert isinstance(locals()[item],func.__annotations__[item])
return (something)
first=7
second="$"
print(func(first,second))
Also check with second=9
(it must give assertion error)
Since PHP 5.4 there are constants which can be used by json_encode()
to format the json reponse how you want.
To remove backslashes use: JSON_UNESCAPED_SLASHES
. Like so:
json_encode($response, JSON_UNESCAPED_SLASHES);
View the PHP documentation for more constants and further information:
http://php.net/manual/en/function.json-encode.php
List of JSON constants:
I know this is old, but if anyone else wants to know why they get incomplete json like above is because the ampersand &
is a special character in URLs used to separate parameters.
In your data there is an ampersand in R&R
. So the acc parameter ends when it reaches the ampersand character.
That's why you are getting chopped data. The solution is either url encode the data or send as POST like the accepted solution suggests.
Depending on your exact needs, you may consider using BitTorrent Sync. Create a shared folder on your home PC and your work PC. Edit the files on your home PC (using Sublime or whatever you like), and they will sync automatically when you save. BitTorrent Sync does not rely on a central server storing the files (a la Dropbox and the like), so you should in theory be clear of any issues due to a third party storing sensitive info.
from jQuery v1.6 use prop
to check that is checkd or not
$('input:radio').prop('checked') // will return true or false
and to make it checkd use
$("input").prop("checked", true);
Another powershell method (I only wanted failures)
$ping = new-object System.Net.NetworkInformation.Ping
$target="192.168.0.1"
Write-Host "$(Get-Date -format 's') Start ping to $target"
while($true){
$reply = $ping.send($target)
if ($reply.status -eq "Success"){
# ignore success
Start-Sleep -Seconds 1
}
else{
Write-Host "$(Get-Date -format 's') Destination unreachable" $target
}
}
You can find something about this in the Adobe Developer FAQ. (It's a PDF document rather than a web page, which I guess is unsurprising in this particular case.)
The FAQ notes that the use of the command line switches is unsupported.
To open a file it's:
AcroRd32.exe <filename>
The following switches are available:
/n
- Launch a new instance of Reader even if one is already open/s
- Don't show the splash screen/o
- Don't show the open file dialog/h
- Open as a minimized window/p <filename>
- Open and go straight to the print dialog/t <filename> <printername> <drivername> <portname>
- Print the file the specified printer.If you had a link I could look to see what the issue is but here are a couple questions and things to check:
Also, if you're going to use the Google CDN for getting jQuery you may as well use Microsoft's CDN for getting your validation file. Any of these URLs will work:
You can use extension methods to achive this.
public static ObjRemoverExtension {
public static void DeleteObj<T>(this T obj) where T: new()
{
obj = null;
}
}
And then you just import it in a desired source file and use on any object. GC will collect it. Like this:Car.DeleteObj()
EDIT Sorry didn't notice the method of class/all references part, but i'll leave it anyway.
FWIW, node.js comes with a shell, try typing in:
node-repl
once you've installed node.js to see it in action. It's pretty standard to install rlwrap to get it to work nicely.
If you want to change only the Back Arrow BUT on the entire app, do this:
[[NSClassFromString(@"_UINavigationBarBackIndicatorView") appearance]
setTintColor:[UIColor colorWithHexString: @"#f00000"]];
#!/bin/bash
goclean() {
local pkg=$1; shift || return 1
local ost
local cnt
local scr
# Clean removes object files from package source directories (ignore error)
go clean -i $pkg &>/dev/null
# Set local variables
[[ "$(uname -m)" == "x86_64" ]] \
&& ost="$(uname)";ost="${ost,,}_amd64" \
&& cnt="${pkg//[^\/]}"
# Delete the source directory and compiled package directory(ies)
if (("${#cnt}" == "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
elif (("${#cnt}" > "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
fi
# Reload the current shell
source ~/.bashrc
}
Usage:
# Either launch a new terminal and copy `goclean` into the current shell process,
# or create a shell script and add it to the PATH to enable command invocation with bash.
goclean github.com/your-username/your-repository
Pymongo 3.9+
update()
is now deprecated and you should use replace_one()
, update_one()
, or update_many()
instead.
In my case I used update_many()
and it solved my issue:
db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)
From documents
update_many(filter, update, upsert=False, array_filters=None, bypass_document_validation=False, collation=None, session=None) filter: A query that matches the documents to update. update: The modifications to apply. upsert (optional): If True, perform an insert if no documents match the filter. bypass_document_validation (optional): If True, allows the write to opt-out of document level validation. Default is False. collation (optional): An instance of Collation. This option is only supported on MongoDB 3.4 and above. array_filters (optional): A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+. session (optional): a ClientSession.
One alternative to using Tensorflow C++ API I found is to use cppflow.
It's a lightweight C++ wrapper around Tensorflow C API. You get very small executables and it links against the libtensorflow.so
already compiled file. There are also examples of use and you use CMAKE instead of Bazel.
i forgot to add below line to my HTML code after i add problem has resolved.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
You have to repeat your expression everywhere you want to use it:
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
or you can make it a subquery
select P
from (
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
) t
WHERE P LIKE 'NW101%'
You must have got the idea why you are getting this problem after going through above answers.
self.send_header('Access-Control-Allow-Origin', '*')
You just have to add the above line in your server side.
I tried a fast and simple thing:
I have two packages -> app.gui
and app.login
In my login class I use the mainview.fxml
from app.gui
so I did this in the login.fxml
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../gui/MainView.fxml"));
And it works :)
I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.
If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.
Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.
However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.
// a = b + c
Complex a, b, c; a = b.add(c);
This is how the ORM maps blank
& null
fields for Django 1.8
class Test(models.Model):
charNull = models.CharField(max_length=10, null=True)
charBlank = models.CharField(max_length=10, blank=True)
charNullBlank = models.CharField(max_length=10, null=True, blank=True)
intNull = models.IntegerField(null=True)
intBlank = models.IntegerField(blank=True)
intNullBlank = models.IntegerField(null=True, blank=True)
dateNull = models.DateTimeField(null=True)
dateBlank = models.DateTimeField(blank=True)
dateNullBlank = models.DateTimeField(null=True, blank=True)
The database fields created for PostgreSQL 9.4 are :
CREATE TABLE Test (
id serial NOT NULL,
"charNull" character varying(10),
"charBlank" character varying(10) NOT NULL,
"charNullBlank" character varying(10),
"intNull" integer,
"intBlank" integer NOT NULL,
"intNullBlank" integer,
"dateNull" timestamp with time zone,
"dateBlank" timestamp with time zone NOT NULL,
"dateNullBlank" timestamp with time zone,
CONSTRAINT Test_pkey PRIMARY KEY (id)
)
The database fields created for MySQL 5.6 are :
CREATE TABLE Test (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`charNull` VARCHAR(10) NULL DEFAULT NULL,
`charBlank` VARCHAR(10) NOT NULL,
`charNullBlank` VARCHAR(10) NULL DEFAULT NULL,
`intNull` INT(11) NULL DEFAULT NULL,
`intBlank` INT(11) NOT NULL,
`intNullBlank` INT(11) NULL DEFAULT NULL,
`dateNull` DATETIME NULL DEFAULT NULL,
`dateBlank` DATETIME NOT NULL,
`dateNullBlank` DATETIME NULL DEFAULT NULL
)
You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.
This problem can occur when you reference your web.config (or app.config) connection strings by index...
var con = ConfigurationManager.ConnectionStrings[0].ConnectionString;
The zero based connection string is not always the one in your config file as it inherits others by default from further up the stack.
The recommended approaches are to access your connection by name...
var con = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
or to clear the connnectionStrings element in your config file first...
<connectionStrings>
<clear/>
<add name="MyConnection" connectionString="...
I prefer using pip in case you are using virtualenv:
apt install libpython2.7 libpython2.7-dev
pip install psycopg2
This worked for me.
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// disable swipe
if(!swipeEnabled) {
if (viewPager.getAdapter().getCount()>1) {
viewPager.setCurrentItem(1);
viewPager.setCurrentItem(0);
}
}
}
public void onPageScrollStateChanged(int state) {}
public void onPageSelected(int position) {}
};
viewPager.addOnPageChangeListener(onPageChangeListener);
Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode
-Version 2
or higher is active. Parenthesised arguments are used in .NET methods only.
function foo($a, $b, $c) {
"a: $a; b: $b; c: $c"
}
ps> foo 1 2 3
a: 1; b: 2; c: 3
I would suggest overriding the equals(Object)
of your Party
class. It might look something like this:
public boolean equals(Object o){
if(o == null)
return false;
if(o instanceof String)
return name.equalsIgnoreCase((String)o);
else if(o instanceof Party)
return equals(((Party)o).name);
return false;
}
After you do that, you could use the indexOf(Object)
method to retrieve the index of the party specified by its name, as shown below:
int index = cave.parties.indexOf("SecondParty");
Would return the index of the Party
with the name SecondParty
.
Note: This only works because you are overriding the equals(Object)
method.
from Xlib import X, display
d = display.Display()
s = d.screen()
root = s.root
root.warp_pointer(300,300)
d.sync()
I found this useful to read from a specific column and row:
FileStream stream = File.Open(@"C:\Users\Desktop\ExcelDataReader.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.IsFirstRowAsColumnNames = true;
DataTable dt = result.Tables[0];
string text = dt.Rows[1][0].ToString();
I had the same problem. solved it like this:
return new ModelAndView("redirect:/user/list?success=true");
And then my controller method look like this:
public ModelMap list(@RequestParam(required=false) boolean success) {
ModelMap mm = new ModelMap();
mm.put(SEARCH_MODEL_KEY, campaignService.listAllCampaigns());
if(success)
mm.put("successMessageKey", "campaign.form.msg.success");
return mm;
}
Works perfectly unless you want to send simple data, not collections let's say. Then you'd have to use session I guess.
All latest versions of mongodb updateMany() is working fine
db.getCollection('workers').updateMany({},{$set: {"assignedVehicleId" : "45680"}});
A solution without reference to a Bean:
<h:button value="login"
outcome="content/configuration.xhtml?i=1" />
In my project I needed this approach:
<h:commandButton value="login"
action="content/configuration.xhtml?faces-redirect=true&i=1" />
import imutils
vs = VideoStream(src=0).start()
...
while (1):
frame = vs.read()
...
frame = imutils.rotate(frame, 45)
Open a terminal and take a look at:
/Applications/Python 3.6/Install Certificates.command
Python 3.6 on MacOS uses an embedded version of OpenSSL, which does not use the system certificate store. More details here.
(To be explicit: MacOS users can probably resolve by opening Finder and double clicking Install Certificates.command)
To collect in a mutable list:
targetList = sourceList.stream()
.filter(i -> i > 100) //apply filter
.collect(Collectors.toList());
To collect in a immutable list:
targetList = sourceList.stream()
.filter(i -> i > 100) //apply filter
.collect(Collectors.toUnmodifiableList());
Explanation of collect
from the JavaDoc:
Performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning. If the stream is parallel, and the Collector is concurrent, and either the stream is unordered or the collector is unordered, then a concurrent reduction will be performed (see Collector for details on concurrent reduction.)
This is a terminal operation.
When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.
You could either use a negative look-ahead or look-behind:
^(?!.*?bar).*
^(.(?<!bar))*?$
Or use just basics:
^(?:[^b]+|b(?:$|[^a]|a(?:$|[^r])))*$
These all match anything that does not contain bar
.
You can do it programatically:
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class ActivityName extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// remove title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
}
Or you can do it via your AndroidManifest.xml
file:
<activity android:name=".ActivityName"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>
Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.
Use facebook feed dialog instead of share dialog.
Example:
You can easily solve this problem by getting the latest version of the Firebase Libraries for Android SDK.
You can get the latest library from https://firebase.google.com/docs/android/setup
Example:
Before:
implementation 'com.google.firebase:firebase-auth:10.6.0'
to
After:
implementation 'com.google.firebase:firebase-auth:16.0.4'
There is nothing in include/require that prohibits you from using absolute an path. so your example
include('/includes/header.php');
should work just fine. Assuming the path and file are corect and have the correct permissions set.
(and thereby allow you to include whatever file you like, in- or outside your document root)
This behaviour is however considered to be a possible security risk. Therefore, the system administrator can set the open_basedir directive.
This directive configures where you can include/require your files from and it might just be your problem.
Some control panels (plesk for example) set this directive to be the same as the document root by default.
as for the '.'
syntax:
/home/username/public_html <- absolute path public_html <- relative path ./public_html <- same as the path above ../username/public_html <- another relative path
However, I usually use a slightly different option:
require_once(__DIR__ . '/Factories/ViewFactory.php');
With this edition, you specify an absolute path, relative to the file that contains the require_once()
statement.
Use list comprehension.
Short circuiting the creation of iterable using a list for example :)
>>> x = [1, 2, 3, 4]
>>>
>>> k = x.__iter__()
>>> k
<listiterator object at 0x100517490>
>>> l = [y for y in k]
>>> l
[1, 2, 3, 4]
>>>
>>> z = Set([1,2])
>>> z.update(l)
>>> z
set([1, 2, 3, 4])
>>>
[Edit: missed the set part of question]
You install as assemblies by using:
gacutil.exe
tool with the -i
option from the command line.%windir%\Assembly
(only up to .NET 3.5, CLR 2.0)You view the content of the GAC using:
gacutil.exe
tool with the -l
option.%windir%\assembly
using the Windows Explorer.Note that the (physical) GAC location has changed for .NET 4.0. It is no longer in %windir%\Assembly
, but now in %windir%\Microsoft.NET\assembly
. However, you should never write any code that depends on the physical location anyway, because given the tools available that is hardly necessary (some "cool" homegrown system diagnostics tools aside).
The problem may be if you are using older version of jQuery. Because older versions of jQuery have 'live' method instead of 'on'
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
Consider the Simple Program listed below,
//we create object user
let User = { name: 'Justin' };
//a Hello Function is created to Alert the object User
function Hello() {
alert(this.name);
}
//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();
//we create an instance to refer the this keyword (this.name);
My implementation of encoding object as query string, using reduce
:
export const encodeAsQueryString = (params) => (
Object.keys(params).reduce((acc, key)=>(
params.hasOwnProperty(key) ? (
[...acc, encodeURIComponent(key) + '=' + encodeURIComponent(params[key])]
) : acc
), []).join('&')
);
for some reasons IS NULL may not work with some column data type i was in need to get all the employees that their English full name is missing ,I've used :
**SELECT emp_id ,Full_Name_Ar,Full_Name_En from employees where Full_Name_En = ' ' or Full_Name_En is null **
Referencing Qwerty's answer, you can avoid to inflate XL size by re-using cellStyle
.
And when the type is CELL_TYPE_BLANK
, getStringCellValue
returns ""
instead of null
.
private static void copyRow(Sheet worksheet, int sourceRowNum, int destinationRowNum) {
// Get the source / new row
Row newRow = worksheet.getRow(destinationRowNum);
Row sourceRow = worksheet.getRow(sourceRowNum);
// If the row exist in destination, push down all rows by 1 else create a new row
if (newRow != null) {
worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);
} else {
newRow = worksheet.createRow(destinationRowNum);
}
// Loop through source columns to add to new row
for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
// Grab a copy of the old/new cell
Cell oldCell = sourceRow.getCell(i);
Cell newCell = newRow.createCell(i);
// If the old cell is null jump to next cell
if (oldCell == null) {
newCell = null;
continue;
}
// Use old cell style
newCell.setCellStyle(oldCell.getCellStyle());
// If there is a cell comment, copy
if (newCell.getCellComment() != null) {
newCell.setCellComment(oldCell.getCellComment());
}
// If there is a cell hyperlink, copy
if (oldCell.getHyperlink() != null) {
newCell.setHyperlink(oldCell.getHyperlink());
}
// Set the cell data type
newCell.setCellType(oldCell.getCellType());
// Set the cell data value
switch (oldCell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
newCell.setCellValue(oldCell.getRichStringCellValue());
break;
}
}
}
And, if you don't want to instantiate Class2, declare UpdateEmployee as static and call it like this:
Class2.UpdateEmployee();
However, you'll normally want to do what @parag said.
One should not specify AUTOINCREMENT
keyword near PRIMARY KEY
.
Example of creating autoincrement primary key and inserting:
$ sqlite3 ex1
CREATE TABLE IF NOT EXISTS room(room_id INTEGER PRIMARY KEY, name VARCHAR(25) NOT NULL, home_id VARCHAR(25) NOT NULL);
INSERT INTO room(name, home_id) VALUES ('test', 'home id test');
INSERT INTO room(name, home_id) VALUES ('test 2', 'home id test 2');
SELECT * FROM room;
will give:
1|test|home id test
2|test 2|home id test 2
function normalexport() {
try {
var i;
var j;
var mycell;
var tableID = "tblInnerHTML";
var drop = document.getElementById('<%= ddl_sections.ClientID %>');
var objXL = new ActiveXObject("Excel.Application");
var objWB = objXL.Workbooks.Add();
var objWS = objWB.ActiveSheet;
var str = filterNum(drop.options[drop.selectedIndex].text);
objWB.worksheets("Sheet1").activate; //activate dirst worksheet
var XlSheet = objWB.activeSheet; //activate sheet
XlSheet.Name = str; //rename
for (i = 0; i < document.getElementById("ctl00_ContentPlaceHolder1_1").rows.length - 1; i++) {
for (j = 0; j < document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells.length; j++) {
mycell = document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells(j);
objWS.Cells(i + 1, j + 1).Value = mycell.innerText;
// objWS.Cells(i + 1, j + 1).style.backgroundColor = mycell.style.backgroundColor;
}
}
objWS.Range("A1", "L1").Font.Bold = true;
// objWS.Range("A1", "L1").Font.ColorIndex = 2;
// objWS.Range("A1", "Z1").Interior.ColorIndex = 47;
objWS.Range("A1", "Z1").EntireColumn.AutoFit();
//objWS.Range("C1", "C1").ColumnWidth = 50;
objXL.Visible = true;
} catch (err) {
alert("Error. Scripting for ActiveX might be disabled")
return
}
idTmr = window.setInterval("Cleanup();", 1);
}
function filterNum(str) {
return str.replace(/[ / ]/g, '');
}
I wouldn't use BigDecimal if you care about performance. BigDecimal converts numbers to string and then parses it back again:
/** Constructs a `BigDecimal` using the decimal text representation of `Double` value `d`, rounding if necessary. */
def decimal(d: Double, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(java.lang.Double.toString(d), mc), mc)
I'm going to stick to math manipulations as Kaito suggested.
In Tomcat 7, you can use "aliases" property. From the docs:
This attribute provides a list of external locations from which to load resources for this context. The list of aliases should be of the form "/aliasPath1=docBase1,/aliasPath2=docBase2" where aliasPathN must include a leading '/' and docBaseN must be an absolute path to either a .war file or a directory. A resource will be searched for in the first docBaseN for which aliasPathN is a leading path segment of the resource. If there is no such alias, then the resource will be searched in the usual way. These external locations will not be emptied if the context is un-deployed.
Like the rest of the users say it is easiest to do this with CURL.
If curl isn't available for you then maybe http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
If that isn't possible you could write sockets yourself http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html
I was facing the same issue and I tried all the above answers. But unfortunately, none of the above worked.
As a note, I finally solve this by pip uninstall distribute
.
I will quickly complement for cases where the header contains emojis, in that case it is simpler to just remove the emoji in the link of the reference. For example
# ? Title 2
....
[Take me to title 2](#-title-2)
There are some cases where this does not work for a weird reason, for example here in setup. The solution in that case is to include the whole code for the emoji as well.
You can use the ternary operator notation:
<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">
Unless you really must implement your own solution, you can use std::minmax_element. This returns a pair of iterators, one to the smallest element and one to the largest.
#include <algorithm>
auto minmax = std::minmax_element(std::begin(values), std::end(values));
std::cout << "min element " << *(minmax.first) << "\n";
std::cout << "max element " << *(minmax.second) << "\n";
I accepted trebleCode's answer, but I wanted to provide a bit more detail regarding the steps I took to install the nupkg of interest pswindowsupdate.2.0.0.4.nupkg
on my unconnected Win 7 machine by way of following trebleCode's answer.
First: after digging around a bit, I think I found the MS docs that trebleCode refers to:
Bootstrap the NuGet provider and NuGet.exe
To continue, as trebleCode stated, I did the following
Install NuGet provider on my connected machine
On a connected machine (Win 10 machine), from the PS command line, I ran Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force
. The Nuget software was obtained from the 'Net and installed on my local connected machine.
After the install I found the NuGet provider software at C:\Program Files\PackageManagement\ProviderAssemblies
(Note: the folder name \ProviderAssemblies
as opposed to \ReferenceAssemblies
was the one minor difference relative to trebleCode's answer.
The provider software is in a folder structure like this:
C:\Program Files\PackageManagement\ProviderAssemblies
\NuGet
\2.8.5.208
\Microsoft.PackageManagement.NuGetProvider.dll
Install NuGet provider on my unconnected machine
I copied the \NuGet folder (and all its children) from the connected machine onto a thumb drive and copied it to C:\Program Files\PackageManagement\ProviderAssemblies
on my unconnected (Win 7) machine
I started PS (v5) on my unconnected (Win 7) machine and ran Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201
to import the provider to the current PowerShell
session.
I ran Get-PackageProvider -ListAvailable
and saw this (NuGet appears where it was not present before):
Name Version DynamicOptions
---- ------- --------------
msi 3.0.0.0 AdditionalArguments
msu 3.0.0.0
NuGet 2.8.5.208 Destination, ExcludeVersion, Scope, SkipDependencies, Headers, FilterOnTag, Contains, AllowPrereleaseVersions, ConfigFile, SkipValidate
PowerShellGet 1.0.0.1 PackageManagementProvider, Type, Scope, AllowClobber, SkipPublisherCheck, InstallUpdate, NoPathUpdate, Filter, Tag, Includes, DscResource, RoleCapability, Command, PublishLocati...
Programs 3.0.0.0 IncludeWindowsInstaller, IncludeSystemComponent
Create local repository on my unconnected machine
On unconnected (Win 7) machine, I created a folder to serve as my PS repository (say, c:\users\foo\Documents\PSRepository
)
I registered the repo: Register-PSRepository -Name fooPsRepository -SourceLocation c:\users\foo\Documents\PSRepository -InstallationPolicy Trusted
Install the NuGet package
I obtained and copied the nupkg pswindowsupdate.2.0.0.4.nupkg
to c:\users\foo\Documents\PSRepository
on my unconnected Win7 machine
I learned the name of the module by executing Find-Module -Repository fooPsRepository
Version Name Repository Description
------- ---- ---------- -----------
2.0.0.4 PSWindowsUpdate fooPsRepository This module contain functions to manage Windows Update Client.
I installed the module by executing Install-Module -Name pswindowsupdate
I verified the module installed by executing Get-Command –module PSWindowsUpdate
CommandType Name Version Source
----------- ---- ------- ------
Alias Download-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Get-WUInstall 2.0.0.4 PSWindowsUpdate
Alias Get-WUList 2.0.0.4 PSWindowsUpdate
Alias Hide-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Install-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Show-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias UnHide-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Uninstall-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Cmdlet Add-WUServiceManager 2.0.0.4 PSWindowsUpdate
Cmdlet Enable-WURemoting 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUApiVersion 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUHistory 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUInstallerStatus 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUJob 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WULastResults 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WURebootStatus 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUServiceManager 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUSettings 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUTest 2.0.0.4 PSWindowsUpdate
Cmdlet Invoke-WUJob 2.0.0.4 PSWindowsUpdate
Cmdlet Remove-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Cmdlet Remove-WUServiceManager 2.0.0.4 PSWindowsUpdate
Cmdlet Set-WUSettings 2.0.0.4 PSWindowsUpdate
Cmdlet Update-WUModule 2.0.0.4 PSWindowsUpdate
I think I'm good to go
No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name="mapping">
<item key="1" v1="A" v2="B" />
<item key="2" v1="X" v2="Y" />
</xsl:variable>
<xsl:variable name="mappingNode"
select="document('')//xsl:variable[@name = 'mapping']" />
<xsl:template match="....">
<xsl:variable name="testVariable" select="'1'" />
<xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />
<xsl:variable name="variable1" select="$values/@v1" />
<xsl:variable name="variable2" select="$values/@v2" />
</xsl:template>
</xsl:stylesheet>
In fact, once you've got the values
variable, you may not even need separate variable1
and variable2
variables. You could just use $values/@v1
and $values/@v2
instead.
Just add the function reference to the $scope in the controller:
for example if you want the function MyFunction to work in ng-click just add to the controller:
app.controller("MyController", ["$scope", function($scope) {
$scope.MyFunction = MyFunction;
}]);
When setting with JQM
, don't forget to update the UI
:
$('#selectId').val('newValue').selectmenu('refresh', true);
Above code made a little cleaner. InputStreams have finally close wrapping to ensure they get closed as well:
*Note
Input: InputStream is, int w, int h
Output: Bitmap
try
{
final int inWidth;
final int inHeight;
final File tempFile = new File(temp, System.currentTimeMillis() + is.toString() + ".temp");
{
final FileOutputStream tempOut = new FileOutputStream(tempFile);
StreamUtil.copyTo(is, tempOut);
tempOut.close();
}
{
final InputStream in = new FileInputStream(tempFile);
final BitmapFactory.Options options = new BitmapFactory.Options();
try {
// decode image size (decode metadata only, not the whole image)
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
}
finally {
in.close();
}
// save width and height
inWidth = options.outWidth;
inHeight = options.outHeight;
}
final Bitmap roughBitmap;
{
// decode full image pre-resized
final InputStream in = new FileInputStream(tempFile);
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
// calc rought re-size (this is no exact resize)
options.inSampleSize = Math.max(inWidth/w, inHeight/h);
// decode full image
roughBitmap = BitmapFactory.decodeStream(in, null, options);
}
finally {
in.close();
}
tempFile.delete();
}
float[] values = new float[9];
{
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
RectF outRect = new RectF(0, 0, w, h);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
m.getValues(values);
}
// resize bitmap
final Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
return resizedBitmap;
}
catch (IOException e) {
logger.error("Error:" , e);
throw new ResourceException("could not create bitmap");
}
gero's solution worked for me.
In Visual Studios 2012, take the following steps.
- Go to Solution Explorer
- Right click on your project
- Go to Properties
- Configuration Properties -> General
- Platform Toolset -> change to Windows7.1SDK
Write unit tests. You can test a lot of things in Cocoa that might be harder in other frameworks. For example, with UI code, you can generally verify that things are connected as they should be and trust that they'll work when used. And you can set up state & invoke delegate methods easily to test them.
You also don't have public vs. protected vs. private method visibility getting in the way of writing tests for your internals.
Sample code from @polyglot solution
SQLiteCommand sql_cmd;
sql_cmd.CommandText = "select seq from sqlite_sequence where name='myTable'; ";
int newId = Convert.ToInt32( sql_cmd.ExecuteScalar( ) );
A simple approach with no third party libraries using Java 7
String path = "your complete file path";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(path)));
byte[] digest = md.digest();
If you need to print this byte array. Use as below
System.out.println(Arrays.toString(digest));
If you need hex string out of this digest. Use as below
String digestInHex = DatatypeConverter.printHexBinary(digest).toUpperCase();
System.out.println(digestInHex);
where DatatypeConverter is javax.xml.bind.DatatypeConverter
Note: this only works for low characters i.e. below 0x8000, This works for all ASCII characters.
I would do an XOR each charAt() to create a new String. Like
String s, key;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++)
sb.append((char)(s.charAt(i) ^ key.charAt(i % key.length())));
String result = sb.toString();
In response to @user467257's comment
If your input/output is utf-8 and you xor "a" and "æ", you are left with an invalid utf-8 string consisting of one character (decimal 135, a continuation character).
It is the char
values which are being xor'ed, but the byte values and this produces a character whichc an be UTF-8 encoded.
public static void main(String... args) throws UnsupportedEncodingException {
char ch1 = 'a';
char ch2 = 'æ';
char ch3 = (char) (ch1 ^ ch2);
System.out.println((int) ch3 + " UTF-8 encoded is " + Arrays.toString(String.valueOf(ch3).getBytes("UTF-8")));
}
prints
135 UTF-8 encoded is [-62, -121]
Just posting a some else solution)
function flatMultidimensionalArray(array &$_arr): array
{
$result = [];
\array_walk_recursive($_arr, static function (&$value, &$key) use (&$result) {
$result[$key] = $value;
});
return $result;
}
private void cleanlistbox(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
I do like below to :
var book: MutableList<Books> = mutableListOf()
/** Returns a new [MutableList] with the given elements. */
public fun <T> mutableListOf(vararg elements: T): MutableList<T>
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
Use the Dir class or opendir()
and readdir()
in a recursive function.
http://www.php.net/manual/en/class.dir.php
jar xf myFile.jar
change myFile to name of your file
this will save the contents in the current folder of .jar file
that should do :)
2GB and about 15M records is a very small database - I've run much bigger ones on a pentium III(!) and everything has still run pretty fast.. If yours is slow it is a database/application design problem, not a mysql one.
Prior to PHP 7 type hinting can only be used to force the types of objects and arrays. Scalar types are not type-hintable. In this case an object of the class string
is expected, but you're giving it a (scalar) string
. The error message may be funny, but it's not supposed to work to begin with. Given the dynamic typing system, this actually makes some sort of perverted sense.
You can only manually "type hint" scalar types:
function foo($string) {
if (!is_string($string)) {
trigger_error('No, you fool!');
return;
}
...
}
I know it's old post, but I thought this is a good addition:
You can use List<T>.ConvertAll<TOutput>
List<int> integers = strings.ConvertAll(s => Int32.Parse(s));
I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.
I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.
Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block
, so when one is pushed down the hole line is pushed down with him. Float fixes this:
#header button {
float:left;
}
Here's a working jsfidle.
Developers also take care about accessibility.
Do not use onClick
on images without defining the ARIA role.
Non-interactive HTML elements and non-interactive ARIA roles indicate content and containers in the user interface. A non-interactive element does not support event handlers (mouse and key handlers).
The developer and designers are responsible for providing the expected behavior of an element that the role suggests it would have: focusability and key press support. More info see WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets.
tldr; this is how it should be done:
<img
src="pond1.jpg"
alt="pic id code"
onClick="window.open(this.src)"
role="button"
tabIndex="0"
/>
In response to this comment I made a filter for Color Filter plugin for Compiz.
Here's what I got:
Howto:
Filter code:
!!ARBfp1.0
TEMP temp, neg;
# Dunno what's this... but every other filter starts with this :) ;
TEX temp, fragment.texcoord[0], texture[0], RECT;
# Applying negative filter ;
RCP neg.a, temp.a;
MAD temp.rgb, -neg.a, temp, 1.0;
MUL temp.rgb, temp.a, temp;
MUL temp, fragment.color, temp;
# Lowering contrast and shifting brightness ;
MUL temp.rgb, temp, 0.8;
ADD temp.rgb, temp, 0.25;
MOV result.color, temp;
END
You also can play with the filter. May be you will get something more facinating :) Feel free to share!
I had the same problem. I decided in a very unexpected way. Just opened the command line as an administrator. And then typed:
pip install numpy
Example to set in the "V" environment variable the most recent file
FOR /F %I IN ('DIR *.* /O:D /B') DO SET V=%I
in a batch file you have to use double prefix in the loop variable:
FOR /F %%I IN ('DIR *.* /O:D /B') DO SET V=%%I
In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:
SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])
I spent almost 6 hours before I stumble on the post.
A simple example of escaping quotes in the shell:
$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc
It's done by finishing an already-opened one ('
), placing the escaped one (\'
), and then opening another one ('
).
Alternatively:
$ echo 'abc'"'"'abc'
abc'abc
$ echo "abc"'"'"abc"
abc"abc
It's done by finishing already opened one ('
), placing a quote in another quote ("'"
), and then opening another one ('
).
More examples: Escaping single-quotes within single-quoted strings
In practice, there are two differences:
cout
in C++ or printf
in C): unsigned integer bit representation is interpreted as a nonnegative integer by print functions.this code can identify the integer using ordering criterion:
char a = 0;
a--;
if (0 < a)
printf("unsigned");
else
printf("signed");
char
is considered signed
in some compilers and unsigned
in other compilers. The code above determines which one is considered in a compiler, using the ordering criterion. If a
is unsigned, after a--
, it will be greater than 0
, but if it is signed
it will be less than zero. But in both cases, the bit representation of a
is the same. That is, in both cases a--
does the same change to the bit representation.
I am not sure whether the database backup file, you trying to restore, is coming from the same environment as you trying to restore it onto.
Remember that destination path of .mdf and .ldf files lives with the backup file itself.
If this is not a case, that means the backup file is coming from a different environment from your current hosting one, make sure that .mdf and .ldf file path is the same (exists) as on your machine, relocate these otherwise. (Mostly a case of restoring db in Docker image)
The way how to do it: In Databases -> Restore database -> [Files] option -> (Check "Relocate all files to folder" - mostly default path is populated on your hosting environment already)
Try quoting the argument list:
Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"
You can also provide the argument list as an array (comma separated args) but using a string is usually easier.
Specifically, document.all
was introduced for IE4 BEFORE document.getElementById
had been introduced.
So, the presence of document.all
means that the code is intended to support IE4, or is trying to identify the browser as IE4 (though it could have been Opera), or the person who wrote (or copied and pasted) the code wasn't up on the latest.
In the highly unlikely event that you need to support IE4, then, you do need document.all
(or a library that handles these ancient IE specs).
Here's the best answer, and the easiest! Put an extra password field in front of your input
field and set the display:none
, so that when the browser fills it in, it does it in an input
that you don't care about.
Change this:
<input type="password" name="password" size="25" class="input" id="password" value="">
to this:
<input type="password" style="display:none;">
<input type="password" name="password" size="25" class="input" id="password" value="">
The following seemed to work well for me:
=DATEDIF(B2, Today(), "D")
Since main()
runs asynchronously it returns a promise. You have to get the result in then()
method. And because then()
returns promise too, you have to call process.exit()
to end the program.
main()
.then(
(text) => { console.log('outside: ' + text) },
(err) => { console.log(err) }
)
.then(() => { process.exit() } )
im using following module:
#!/usr/bin/python
# module for getting the lan ip address of the computer
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', bytes(ifname[:15], 'utf-8'))
# Python 2.7: remove the second argument for the bytes call
)[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break;
except IOError:
pass
return ip
Tested with windows and linux (and doesnt require additional modules for those) intended for use on systems which are in a single IPv4 based LAN.
The fixed list of interface names does not work for recent linux versions, which have adopted the systemd v197 change regarding predictable interface names as pointed out by Alexander. In such cases, you need to manually replace the list with the interface names on your system, or use another solution like netifaces.
.a files are usually libraries which get statically linked (or more accurately archives), and
.so are dynamically linked libraries.
To do a port you will need the source code that was compiled to make them, or equivalent files on your AIX machine.
-z
string is null, that is, has zero length
String='' # Zero-length ("null") string variable.
if [ -z "$String" ]
then
echo "\$String is null."
else
echo "\$String is NOT null."
fi # $String is null.