Page Control can be contained in Window Control but vice versa is not possible
You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer).
WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.
it clears stdin
buffer before reading. From the man page:
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.
Note: This is Linux-specific, using fflush()
on input streams is undefined by the standard, however, most implementations behave the same as in Linux.
My problem is cookies are not working "within" the same session. –
Burak: I had the same problem. Enabling cookies fixed the issue.
CookieManager.getInstance().setAcceptCookie(true);
I am using xampp. For me best option is to change environment variables. Environment variable changing window is shared by @Abu Bakr in this thread
I change the path value as C:\xampp\mysql\bin; and it is working nice
The mutable
keyword is a way to pierce the const
veil you drape over your objects. If you have a const reference or pointer to an object, you cannot modify that object in any way except when and how it is marked mutable
.
With your const
reference or pointer you are constrained to:
const
. The mutable
exception makes it so you can now write or set data members that are marked mutable
. That's the only externally visible difference.
Internally those const
methods that are visible to you can also write to data members that are marked mutable
. Essentially the const veil is pierced comprehensively. It is completely up to the API designer to ensure that mutable
doesn't destroy the const
concept and is only used in useful special cases. The mutable
keyword helps because it clearly marks data members that are subject to these special cases.
In practice you can use const
obsessively throughout your codebase (you essentially want to "infect" your codebase with the const
"disease"). In this world pointers and references are const
with very few exceptions, yielding code that is easier to reason about and understand. For a interesting digression look up "referential transparency".
Without the mutable
keyword you will eventually be forced to use const_cast
to handle the various useful special cases it allows (caching, ref counting, debug data, etc.). Unfortunately const_cast
is significantly more destructive than mutable
because it forces the API client to destroy the const
protection of the objects (s)he is using. Additionally it causes widespread const
destruction: const_cast
ing a const pointer or reference allows unfettered write and method calling access to visible members. In contrast mutable
requires the API designer to exercise fine grained control over the const
exceptions, and usually these exceptions are hidden in const
methods operating on private data.
(N.B. I refer to to data and method visibility a few times. I'm talking about members marked as public vs. private or protected which is a totally different type of object protection discussed here.)
I tried the accepted solution and it didn't work for me. I use the browser debugger and found out the actual height that should be used is the clientHeight
BUT you have to put this into the updated()
hook for the whole solution to work.
data(){
return {
conversation: [
{
}
]
},
mounted(){
EventBus.$on('msg-ctr--push-msg-in-conversation', textMsg => {
this.conversation.push(textMsg)
// Didn't work doing scroll here
})
},
updated(){ <=== PUT IT HERE !!
var elem = this.$el
elem.scrollTop = elem.clientHeight;
},
Just multiply the number by 100, round, and divide the resulting number by 100.
A simple solution:
<a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>
Or
<script>
/** Change the style **/
function overStyle(object){
object.style.color = 'orange';
// Change some other properties ...
}
/** Restores the style **/
function outStyle(object){
object.style.color = 'orange';
// Restore the rest ...
}
</script>
<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>
You have to check unique identifier column and you have to give a diff value to that particular field if you give the same value it will not work. It enforces uniqueness of the key.
Here is the code:
Insert into production.product
(Name,ProductNumber,MakeFlag,FinishedGoodsFlag,Color,SafetyStockLevel,ReorderPoint,StandardCost,ListPrice,Size
,SizeUnitMeasureCode,WeightUnitMeasureCode,Weight,DaysToManufacture,
ProductLine,
Class,
Style ,
ProductSubcategoryID
,ProductModelID
,SellStartDate
,SellEndDate
,DiscontinuedDate
,rowguid
,ModifiedDate
)
values ('LL lemon' ,'BC-1234',0,0,'blue',400,960,0.00,100.00,Null,Null,Null,null,1,null,null,null,null,null,'1998-06-01 00:00:00.000',null,null,'C4244F0C-ABCE-451B-A895-83C0E6D1F468','2004-03-11 10:01:36.827')
My suggestion is to run
openssl enc -aes-256-cbc -in plain.txt -out encrypted.bin
under debugger and see what exactly what it is doing. openssl.c is the only real tutorial/getting started/reference guide OpenSSL has. All other documentation is just an API reference.
U1: My guess is that you are not setting some other required options, like mode of operation (padding).
U2: this is probably a duplicate of this question: AES CTR 256 Encryption Mode of operation on OpenSSL and answers there will likely help.
I believe this is what you were looking for:
class Expression {
protected $expression;
protected $result;
public function __construct($expression) {
$this->expression = $expression;
}
public function evaluate() {
$this->result = eval("return ".$this->expression.";");
return $this;
}
public function getResult() {
return $this->result;
}
}
class NegativeFinder {
protected $expressionObj;
public function __construct(Expression $expressionObj) {
$this->expressionObj = $expressionObj;
}
public function isItNegative() {
$result = $this->expressionObj->evaluate()->getResult();
if($this->hasMinusSign($result)) {
return true;
} else {
return false;
}
}
protected function hasMinusSign($value) {
return (substr(strval($value), 0, 1) == "-");
}
}
Usage:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.
:-)
In answer to the further question -
"is there anyway to apply this within the Visual Studio project? In a multi-developer environment, if someone else check's out the code on their machine, then their local IIS Express wouldn't be configured with the virtual directory and cause runtime errors wouldn't it?"
I never found a consistant answer to this anywhere but then figured out you could do it with a post build event using the XmlPoke task in the project file for the website -
<Target Name="AfterBuild">
<!-- Get the local directory root (and strip off the website name) -->
<PropertyGroup>
<LocalTarget>$(ProjectDir.Replace('MyWebSite\', ''))</LocalTarget>
</PropertyGroup>
<!-- Now change the virtual directories as you need to -->
<XmlPoke XmlInputPath="..\..\Source\Assemblies\MyWebSite\.vs\MyWebSite\config\applicationhost.config"
Value="$(LocalTarget)AnotherVirtual"
Query="/configuration/system.applicationHost/sites/site[@name='MyWebSite']/application[@path='/']/virtualDirectory[@path='/AnotherVirtual']/@physicalPath"/>
</Target>
You can use this technique to repoint anything in the file before IISExpress starts up. This would allow you to initially force an applicationHost.config file into GIT (assuming it is ignored by gitignore) then subsequently repoint all the paths at build time. GIT will ignore any changes to the file so it's now easy to share them around.
In answer to the futher question about adding other applications under one site:
You can create the site in your application hosts file just like the one on your server. For example:
<site name="MyWebSite" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\GIT\MyWebSite\Main" />
<virtualDirectory path="/SharedContent" physicalPath="C:\GIT\SharedContent" />
<virtualDirectory path="/ServerResources" physicalPath="C:\GIT\ServerResources" />
</application>
<application path="/AppSubSite" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\GIT\AppSubSite\" />
<virtualDirectory path="/SharedContent" physicalPath="C:\GIT\SharedContent" />
<virtualDirectory path="/ServerResources" physicalPath="C:\GIT\ServerResources" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:4076:localhost" />
</bindings>
</site>
Then use the above technique to change the folder locations at build time.
Using CPromise package we can use the following approach (Live demo)
import CPromise from "c-promise2";
const chain = new CPromise((resolve, reject, { onCancel }) => {
const timer = setTimeout(resolve, 1000, 123);
onCancel(() => clearTimeout(timer));
})
.then((value) => value + 1)
.then(
(value) => console.log(`Done: ${value}`),
(err, scope) => {
console.warn(err); // CanceledError: canceled
console.log(`isCanceled: ${scope.isCanceled}`); // true
}
);
setTimeout(() => {
chain.cancel();
}, 100);
The same thing using AbortController (Live demo)
import CPromise from "c-promise2";
const controller= new CPromise.AbortController();
new CPromise((resolve, reject, { onCancel }) => {
const timer = setTimeout(resolve, 1000, 123);
onCancel(() => clearTimeout(timer));
})
.then((value) => value + 1)
.then(
(value) => console.log(`Done: ${value}`),
(err, scope) => {
console.warn(err);
console.log(`isCanceled: ${scope.isCanceled}`);
}
).listen(controller.signal);
setTimeout(() => {
controller.abort();
}, 100);
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
naturalWidth and naturalHeight
var img = document.createElement("img");
img.onload = function (event)
{
console.log("natural:", img.naturalWidth, img.naturalHeight);
console.log("width,height:", img.width, img.height);
console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);
// css for tests
img { width:50%;height:50%; }
in your .net project go to reference section, right click on Oracle.DataAccess dll, goto properties.
Change the setting to "Specific Version=False
". Now it will be no version conflict
if u want to have multiple selection on select row..
import React from 'react';
import ReactTable from 'react-table';
import 'react-table/react-table.css';
import { ReactTableDefaults } from 'react-table';
import matchSorter from 'match-sorter';
class ThreatReportTable extends React.Component{
constructor(props){
super(props);
this.state = {
selected: [],
row: []
}
}
render(){
const columns = this.props.label;
const data = this.props.data;
Object.assign(ReactTableDefaults, {
defaultPageSize: 10,
pageText: false,
previousText: '<',
nextText: '>',
showPageJump: false,
showPagination: true,
defaultSortMethod: (a, b, desc) => {
return b - a;
},
})
return(
<ReactTable className='threatReportTable'
data= {data}
columns={columns}
getTrProps={(state, rowInfo, column) => {
return {
onClick: (e) => {
var a = this.state.selected.indexOf(rowInfo.index);
if (a == -1) {
// this.setState({selected: array.concat(this.state.selected, [rowInfo.index])});
this.setState({selected: [...this.state.selected, rowInfo.index]});
// Pass props to the React component
}
var array = this.state.selected;
if(a != -1){
array.splice(a, 1);
this.setState({selected: array});
}
},
// #393740 - Lighter, selected row
// #302f36 - Darker, not selected row
style: {background: this.state.selected.indexOf(rowInfo.index) != -1 ? '#393740': '#302f36'},
}
}}
noDataText = "No available threats"
/>
)
}
}
export default ThreatReportTable;
If you want to pass Method as parameter, use:
using System;
public void Method1()
{
CallingMethod(CalledMethod);
}
public void CallingMethod(Action method)
{
method(); // This will call the method that has been passed as parameter
}
public void CalledMethod()
{
Console.WriteLine("This method is called by passing parameter");
}
Refining Günter Zöchbauer answer:
This appears to be different now. I was trying to do this to conditionally apply an href attribute to an anchor tag. You must use undefined for the 'do not apply' case. As an example, I'll demonstrate with a link conditionally having an href attribute applied.
--EDIT--
It looks like angular has changed some things, so null
will now work as expected. I've update the example to use null
rather than undefined
.
An anchor tag without an href attribute becomes plain text, indicating a placeholder for a link, per the hyperlink spec.
For my navigation, I have a list of links, but one of those links represents the current page. I didn't want the current page link to be a link, but still want it to appear in the list (it has some custom styles, but this example is simplified).
<a [attr.href]="currentUrl !== link.url ? link.url : null">
This is cleaner than using two *ngIf's on a span and anchor tag, I think. It's also perfect for adding a disabled attribute to a button.
For kotlin I use the following
val fcmtoken = FirebaseMessaging.getInstance().token.await()
and for the extension functions
public suspend fun <T> Task<T>.await(): T {
// fast path
if (isComplete) {
val e = exception
return if (e == null) {
if (isCanceled) {
throw CancellationException("Task $this was cancelled normally.")
} else {
@Suppress("UNCHECKED_CAST")
result as T
}
} else {
throw e
}
}
return suspendCancellableCoroutine { cont ->
addOnCompleteListener {
val e = exception
if (e == null) {
@Suppress("UNCHECKED_CAST")
if (isCanceled) cont.cancel() else cont.resume(result as T)
} else {
cont.resumeWithException(e)
}
}
}
}
I have a workaround using jquery... although we cannot style a particular option, we can style the select itself - and use javascript to change the class of the select based on what is selected. It works sufficiently for simple cases.
$('select.potentially_red').on('change', function() {_x000D_
if ($(this).val()=='red') {_x000D_
$(this).addClass('option_red');_x000D_
} else {_x000D_
$(this).removeClass('option_red');_x000D_
}_x000D_
});_x000D_
$('select.potentially_red').each( function() {_x000D_
if ($(this).val()=='red') {_x000D_
$(this).addClass('option_red');_x000D_
} else {_x000D_
$(this).removeClass('option_red');_x000D_
}_x000D_
});
_x000D_
.option_red {_x000D_
background-color: #cc0000; _x000D_
font-weight: bold; _x000D_
font-size: 12px; _x000D_
color: white;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<!-- The js will affect all selects which have the class 'potentially_red' -->_x000D_
<select name="color" class="potentially_red">_x000D_
<option value="red">Red</option>_x000D_
<option value="white">White</option>_x000D_
<option value="blue">Blue</option>_x000D_
<option value="green">Green</option>_x000D_
</select>
_x000D_
Note that the js is in two parts, the each
part for initializing everything on the page correctly, the .on('change', ...
part for responding to change. I was unable to mangle the js into a function to DRY it up, it breaks it for some reason
This is all you need:
background-repeat: no-repeat;
Perhaps you need to read about interactive usage of Matplotlib. However, if you are going to build an app, you should be using the API and embedding the figures in the windows of your chosen GUI toolkit (see examples/embedding_in_tk.py
, etc).
I just tried doing this on Chrome:
var $sel = $('#sel'); $sel.find('option').hover(function(){$sel.attr('title',$(this).attr('title'));console.log($(this).attr('title'))}, function(){$sel.attr('title','');});
However, the hover enter never fires... So you wouldn't be able to do this at all using the standard select. You could achieve this though through some non standard ways:
I was in trouble to import an Enum in typescript
error TS2307: Cannot find module...
What I did to make it work was migrate the enum to another file and make this change:
export enum MyEnum{
VALUE = "MY_VALUE"
}
to
export enum MyEnum{
VALUE = 1
}
To give custom parameters to facebook share its better to give only the link and facebook gets its Title + Description + Picture automatically from the page that you are sharing. In order to "help" facebook API find those things you can put the following things in the header of the page that you are sharing:
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
If the page is not under your control use what AllisonC has shared above.
Use your own button/link/text and then you can use a modal view type of popup this way:
<script type= 'text/javascript'>
$('#twitterbtn-link,#facebookbtn-link').click(function(event) {
var width = 575,
height = 400,
left = ($(window).width() - width) / 2,
top = ($(window).height() - height) / 2,
url = this.href,
opts = 'status=1' +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left;
window.open(url, 'twitter', opts);
return false;
});
</script>
where twitterbtn-link and facebookbtn-link are both ids of anchors.
I had this problem, and it is super simple to fix.
Get two containers. The inner will be your scrollable container and the outer will obviously house the inner:
#inner_container { width: 102%; overflow: auto; }
#outer_container { overflow: hidden }
It is super simple and should work with any browser.
Here's my take. One Interesting thing is that we need to check min coins needed to form up to coin_with_max_value(25 in our case) - 1 only. After that just calculate the sum of these min coins. From that point we just need to add certain number of coin_with_max_value, to form any number up to the total cost, depending on the difference of total cost and the sum found out. That's it.
So for values we have take, once min coins for 24 is found out: [1, 2, 2, 5, 10, 10].
We just need to keep adding a 25 coin for every 25 values exceeding 30(sum of min coins).
Final answer for 99 is:
[1, 2, 2, 5, 10, 10, 25, 25, 25]
9
import itertools
import math
def ByCurrentCoins(val, coins):
for i in range(1, len(coins) + 1):
combinations = itertools.combinations(coins, i)
for combination in combinations:
if sum(combination) == val:
return True
return False
def ExtraCoin(val, all_coins, curr_coins):
for c in all_coins:
if ByCurrentCoins(val, curr_coins + [c]):
return c
def main():
cost = 99
coins = sorted([1, 2, 5, 10, 25], reverse=True)
max_coin = coins[0]
curr_coins = []
for c in range(1, min(max_coin, cost+1)):
if ByCurrentCoins(c, curr_coins):
continue
extra_coin = ExtraCoin(c, coins, curr_coins)
if not extra_coin:
print -1
return
curr_coins.append(extra_coin)
curr_sum = sum(curr_coins)
if cost > curr_sum:
extra_max_coins = int(math.ceil((cost - curr_sum)/float(max_coin)))
curr_coins.extend([max_coin for _ in range(extra_max_coins)])
print curr_coins
print len(curr_coins)
There are a lot of ways you can call a shell command from a Perl script, such as:
ls
which captures the output and gives back to you.Refer #17 here: Perl programming tips
def findReplace(find, replace):
import os
src = os.path.join(os.getcwd(), os.pardir)
for path, dirs, files in os.walk(os.path.abspath(src)):
for name in files:
if name.endswith('.py'):
filepath = os.path.join(path, name)
with open(filepath) as f:
s = f.read()
s = s.replace(find, replace)
with open(filepath, "w") as f:
f.write(s)
Don't define the height as a percent, just set the top=0
and bottom=0
, like this:
#div {
top: 0; bottom: 0;
position: absolute;
width: 100%;
}
you can do it in two ways using
Serializable
Parcelable.
This examle will show you how to implement it with serializable
class Customer implements Serializable
{
// properties, getter setters & constructor
}
// This is your custom object
Customer customer = new Customer(name, address, zip);
Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);
startActivity(intent);
// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
Customer customer = (Customer)extras.getSerializable("customer");
// do something with the customer
}
Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.
Look at this.. This discussion will let you know which is much better way to implement it.
Thanks.
you didn't import sys in your code, nor did you close the () when calling the function... try:
import sys
sys.exit()
If you want both of EnsureCreated and Migrate use this code:
using (var context = new YourDbContext())
{
if (context.Database.EnsureCreated())
{
//auto migration when database created first time
//add migration history table
string createEFMigrationsHistoryCommand = $@"
USE [{context.Database.GetDbConnection().Database}];
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
CREATE TABLE [dbo].[__EFMigrationsHistory](
[MigrationId] [nvarchar](150) NOT NULL,
[ProductVersion] [nvarchar](32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY CLUSTERED
(
[MigrationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY];
";
context.Database.ExecuteSqlRaw(createEFMigrationsHistoryCommand);
//insert all of migrations
var dbAssebmly = context.GetType().GetAssembly();
foreach (var item in dbAssebmly.GetTypes())
{
if (item.BaseType == typeof(Migration))
{
string migrationName = item.GetCustomAttributes<MigrationAttribute>().First().Id;
var version = typeof(Migration).Assembly.GetName().Version;
string efVersion = $"{version.Major}.{version.Minor}.{version.Build}";
context.Database.ExecuteSqlRaw("INSERT INTO __EFMigrationsHistory(MigrationId,ProductVersion) VALUES ({0},{1})", migrationName, efVersion);
}
}
}
context.Database.Migrate();
}
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
your question makes no sense. you are asking how to turn a hash into an array. You cant.
you can make a list of values, or make a list of keys, and neither of these have anything to do with jquery, this is pure javascript
To communicate between an Activity
and Fragment
s, there are several options, but after lots of reading and many experiences, I found out that it could be resumed this way:
Activity
wants to communicate with child Fragment
=> Simply write public methods in your Fragment
class, and let the Activity
call themFragment
wants to communicate with the parent Activity
=> This requires a bit more of work, as the official Android link https://developer.android.com/training/basics/fragments/communicating suggests, it would be a great idea to define an interface
that will be implemented by the Activity
, and which will establish a contract for any Activity
that wants to communicate with that Fragment
. For example, if you have FragmentA
, which wants to communicate with any activity
that includes it, then define the FragmentAInterface
which will define what method can the FragmentA
call for the activities
that decide to use it.Fragment
wants to communicate with other Fragment
=> This is the case where you get the most 'complicated' situation. Since you could potentially need to pass data from FragmentA to FragmentB and viceversa, that could lead us to defining 2 interfaces, FragmentAInterface
which will be implemented by FragmentB
and FragmentAInterface
which will be implemented by FragmentA
. That will start making things messy. And imagine if you have a few more Fragment
s on place, and even the parent activity
wants to communicate with them. Well, this case is a perfect moment to establish a shared ViewModel
for the activity
and it's fragment
s. More info here https://developer.android.com/topic/libraries/architecture/viewmodel . Basically, you need to define a SharedViewModel
class, that has all the data you want to share between the activity
and the fragments
that will be in need of communicating data among them.The ViewModel
case, makes things pretty simpler at the end, since you don't have to add extra logic that makes things dirty in the code and messy. Plus it will allow you to separate the gathering (through calls to an SQLite Database or an API) of data from the Controller
(activities
and fragments
).
You just need the jQuery UI effects-core (13KB), to enable the duration of the adding (just like Omar Tariq it pointed out)
You can only install a language pack at install time in VS 2017 RC. To install RC with a different language:
You can have multiple instances of VS 2017 side by side so this shouldn't interfere with your other installation.
Disclosure: I work on Visual Studio at Microsoft.
Isn't easier than doing like :
1- Install jquery in your project:
yarn add jquery
2- Import jquery and start playing with DOM:
import $ from 'jquery';
You can restore to a new DB, verify the file name syntax, it ll be in the log file, for the new SQL version ll be a "_log" suffix
ad check the overwrite the existing database flag in option tab
Fabio
Specifically, this is not rounding your result, it's truncating toward zero. So if you divide -3/2, you'll get -1 and not -2. Welcome to integral math! Back before CPUs could do floating point operations or the advent of math co-processors, we did everything with integral math. Even though there were libraries for floating point math, they were too expensive (in CPU instructions) for general purpose, so we used a 16 bit value for the whole portion of a number and another 16 value for the fraction.
EDIT: my answer makes me think of the classic old man saying "when I was your age..."
That's Media Queries. It allows you to apply part of CSS rules only to the specific devices on specific configuration.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
public void run() {
/* Create an intent that will start the main activity. */
Intent mainIntent = new Intent(SplashScreen.this,
ConnectedActivity.class);
mainIntent.putExtra("id", "1");
//SplashScreen.this.startActivity(mainIntent);
startActivity(mainIntent);
/* Finish splash activity so user cant go back to it. */
SplashScreen.this.finish();
/* Apply our splash exit (fade out) and main
entry (fade in) animation transitions. */
overridePendingTransition(R.anim.mainfadein,R.anim.splashfadeout);
}
}, SPLASH_DISPLAY_TIME);
}
The main reason ++ comes in handy in C-like languages is for keeping track of indices. In Python, you deal with data in an abstract way and seldom increment through indices and such. The closest-in-spirit thing to ++
is the next
method of iterators.
The only difference is that you're creating an unnecessary promise when you do return Promise.resolve("bbb")
. Returning a promise from an onFulfilled()
handler kicks off promise resolution. That's how promise chaining works.
Even though Sheena's answer does the job, pip
doesn't stop just there.
From Sheena's answer:
- Download the package
- unzip it if it is zipped
- cd into the directory containing setup.py
- If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
- type in
python setup.py install
At the end of this, you'll end up with a .egg
file in site-packages
.
As a user, this shouldn't bother you. You can import
and uninstall
the package normally. However, if you want to do it the pip
way, you can continue the following steps.
In the site-packages
directory,
unzip <.egg file>
EGG-INFO
directory as <pkg>-<version>.dist-info
<pkg-directory>
find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD
. The >>
is to prevent overwrite.Now, looking at the site-packages
directory, you'll never realize you installed without pip
. To uninstall
, just do the usual pip uninstall <pkg>
.
I would recommend identifying the functionality you need from any subclasses, and make a generic method to cast into the right subclass.
I had this same problem, but really didn't feel like creating some mapping class or importing a library.
Let's say you need the 'Authenticate' method to take behavior from the right subclass. In your NetworkClient:
protected bool Authenticate(string username, string password) {
//...
}
protected bool DoAuthenticate<T>(NetworkClient nc, string username, string password) where T : NetworkClient {
//Do a cast into the sub class.
T subInst = (T) nc;
return nc.Authenticate(username, password);
}
The question is for linux but I had the same issue with git bash on my Windows machine.
My pqsql is installed here:
C:\Program Files\PostgreSQL\10\bin\psql.exe
You can add the location of psql.exe
to your Path environment variable as shown in this screenshot:
After changing the above, please close all cmd
and/or bash
windows, and re-open them (as mentioned in the comments @Ayush Shankar)
You might need to change default logging user using below command.
psql -U postgres
Here postgres
is the username. Without -U
, it will pick the windows loggedin user.
Found amazing simple solution - working for Chrome (Windows, not tested on Mac)
Zebra ZP 450
Also constructor based initialisation will not work as intended whenever some kind of proxying or remoting is involved.
The ct will get called whenever an EJB gets deserialized, and whenever a new proxy gets created for it...
At the top of your .vb file:
Imports System.data.sqlclient
Within your code:
'Setup SQL Command
Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("@Parameter1", sqlDBType.Int).value = Param_1_value
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'Fill the dataset
Dim DS as DataSet
adapter.Fill(ds)
connection.Close()
'Now, read through your data:
For Each DR as DataRow in DS.Tables(0).rows
Msgbox("The value in Column ""ColumnName1"": " & cstr(DR("ColumnName1")))
next
Now that the basics are out of the way,
I highly recommend abstracting the actual SqlCommand Execution out into a function.
Here is a generic function that I use, in some form, on various projects:
''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD)</summary>'''
''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."),'''
''' otherwise if there is just one token, it's a stored procedure command</param>''''
Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet
Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString
Dim ds As New DataSet()
Try
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers"
If CMD.CommandText.Contains(" ") Then
CMD.CommandType = CommandType.Text
Else
CMD.CommandType = CommandType.StoredProcedure
End If
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'fill the dataset
adapter.Fill(ds)
connection.Close()
Catch ex As Exception
' The connection failed. Display an error message.
Throw New Exception("Database Error: " & ex.Message)
End Try
Return ds
End Function
Once you have that, your SQL Execution + reading code is very simple:
'----------------------------------------------------------------------'
Dim CMD As New SqlCommand("GetProductName")
CMD.Parameters.Add("@productID", SqlDbType.Int).Value = ProductID
Dim DR As DataRow = ExecuteCMD(CMD).Tables(0).Rows(0)
MsgBox("Product Name: " & cstr(DR(0)))
'----------------------------------------------------------------------'
Module rewrite_module is built-in in to the server most cases
Use .htaccess
Use the Mod Rewrite Generator at http://www.generateit.net/mod-rewrite/
Would sending the mail as plain-text sort this?
"How to Send a Plain Text Message in Outlook":
- Select Actions | New Mail Message Using | Plain Text from the menu in Outlook.
- Create your message as usual.
- Click Send to deliver it.
Being plain text it shouldn't screw up your code, with "smart" quotes, auto-capitalisation and such.
Another possible option, if this is a common problem within the company perhaps you could setup an internal code-paste site, there's plenty of open-source ones around, like Open Pastebin
Sure, the [::]
is the extended slice operator. It allows you to take substrings. Basically, it works by specifying which elements you want as [begin:end:step], and it works for all sequences. Two neat things about it:
For begin and end, if you give a negative number, it means to count from the end of the sequence. For instance, if I have a list:
l = [1,2,3]
Then l[-1]
is 3, l[-2]
is 2, and l[-3]
is 1.
For the step
argument, a negative number means to work backwards through the sequence. So for a list::
l = [1,2,3,4,5,6,7,8,9,10]
You could write l[::-1]
which basically means to use a step size of -1 while reading through the list. Python will "do the right thing" when filling in the start and stop so it iterates through the list backwards and gives you [10,9,8,7,6,5,4,3,2,1]
.
I've given the examples with lists, but strings are just another sequence and work the same way. So a[::-1]
means to build a string by joining the characters you get by walking backwards through the string.
static final PcapLinkType[] values = { DLT_NULL, DLT_EN10MB, DLT_EN3MB, null ...}
...
public static PcapLinkType getPcapLinkTypeForInt(int num){
try{
return values[int];
}catch(ArrayIndexOutOfBoundsException e){
return DLT_UKNOWN;
}
}
I searched for this very question and when I saw the answers I ended up creating something different (because I favor less code over most other things most of the time) that should work in the vast majority of cases. Basically turn the array into a string with array elements separated by some delimiter character, and then wrap the search value in the delimiter character and pass through instr.
Function is_in_array(value As String, test_array) As Boolean
If Not (IsArray(test_array)) Then Exit Function
If InStr(1, "'" & Join(test_array, "'") & "'", "'" & value & "'") > 0 _
Then is_in_array = True
End Function
And you'd execute the function like this:
test = is_in_array(1, array(1, 2, 3))
The simplest way is using pip
command:
pip list | grep Keras
Best way to the solution of your problem is to use button block btn-block with desired column width.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="col-md-12">_x000D_
<button class="btn btn-primary btn-block">Save</button>_x000D_
</div>_x000D_
<div class="col-md-12">_x000D_
<button class="btn btn-success btn-block">Download</button>_x000D_
</div>
_x000D_
The maximum values do not depend on Eclipse, it depends on your OS (and obviously on the physical memory available).
You may want to take a look at this question: Max amount of memory per java process in Windows?
In JSP, you'd normally like to use JSTL <fmt:formatDate>
for this. You can of course also throw in a scriptlet with SimpleDateFormat
, but scriptlets are strongly discouraged since 2003.
Assuming that ${bean.date}
returns java.util.Date
, here's how you can use it:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<fmt:formatDate value="${bean.date}" pattern="yyyy-MM-dd HH:mm:ss" />
If you're actually using a java.util.Calendar
, then you can invoke its getTime()
method to get a java.util.Date
out of it that <fmt:formatDate>
accepts:
<fmt:formatDate value="${bean.calendar.time}" pattern="yyyy-MM-dd HH:mm:ss" />
Or, if you're actually holding the date in a java.lang.String
(this indicates a serious design mistake in the model; you should really fix your model to store dates as java.util.Date
instead of as java.lang.String
!), here's how you can convert from one date string format e.g. MM/dd/yyyy
to another date string format e.g. yyyy-MM-dd
with help of JSTL <fmt:parseDate>
.
<fmt:parseDate pattern="MM/dd/yyyy" value="${bean.dateString}" var="parsedDate" />
<fmt:formatDate value="${parsedDate}" pattern="yyyy-MM-dd" />
def concatFiles():
path = 'input/'
files = os.listdir(path)
for idx, infile in enumerate(files):
print ("File #" + str(idx) + " " + infile)
concat = ''.join([open(path + f).read() for f in files])
with open("output_concatFile.txt", "w") as fo:
fo.write(path + concat)
if __name__ == "__main__":
concatFiles()
Here's a suggestion: use two indices into the string, say start
and end
. start
points to the first character of the next string to extract, end
points to the character after the last one belonging to the next string to extract. start
starts at zero, end
gets the position of the first char after start
. Then you take the string between [start..end)
and add that to your array. You keep going until you hit the end of the string.
You can use the following steps, its worked for me to drop table with constraint,solution already explained in the above comment, i just added screen shot for that -
Try this
$('.yourchkboxes').change(function(){
$('.yourbutton').toggle($('.yourchkboxes:checked').length > 0);
});
So it will check for at least one checkbox is checked or not.
After a certain amount of time, your access token expires.
To prevent this, you can request the 'offline_access' permission during the authentication, as noted here: Do Facebook Oauth 2.0 Access Tokens Expire?
As the others have said, you can use var
at global scope (outside of all functions and modules) to declare a global variable:
<script>
var yourGlobalVariable;
function foo() {
// ...
}
</script>
(Note that that's only true at global scope. If that code were in a module — <script type="module">...</script>
— it wouldn't be at global scope, so that wouldn't create a global.)
Alternatively:
In modern environments, you can assign to a property on the object that globalThis
refers to (globalThis
was added in ES2020):
<script>
function foo() {
globalThis.yourGlobalVariable = ...;
}
</script>
On browsers, you can do the same thing with the global called window
:
<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>
...because in browsers, all global variables global variables declared with var
are properties of the window
object. (In the latest specification, ECMAScript 2015, the new let
, const
, and class
statements at global scope create globals that aren't properties of the global object; a new concept in ES2015.)
(There's also the horror of implicit globals, but don't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5's "use strict"
.)
All that said: I'd avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of window
, and window
is already plenty crowded enough what with all elements with an id
(and many with just a name
) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a name
on there).
Instead, in modern environments, use modules:
<script type="module">
let yourVariable = 42;
// ...
</script>
The top level code in a module is at module scope, not global scope, so that creates a variable that all of the code in that module can see, but that isn't global.
In obsolete environments without module support, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:
<script>
(function() { // Begin scoping function
var yourGlobalVariable; // Global to your code, invisible outside the scoping function
function foo() {
// ...
}
})(); // End scoping function
</script>
IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment
Will do the job as Buttle Butkus suggested.
It looks like the cause of the errors are:
You're currently loading the source file in the src
directory instead of the built file in the dist
directory (you can see what the intended distributed file is here). This means that you're using the native source code in an unaltered/unbundled state, leading to the following error: Uncaught SyntaxError: Cannot use import statement outside a module
. This should be fixed by using the bundled version since the package is using rollup to create a bundle.
The reason you're getting the Uncaught ReferenceError: ms is not defined
error is because modules are scoped, and since you're loading the library using native modules, ms
is not in the global scope and is therefore not accessible in the following script tag.
It looks like you should be able to load the dist
version of this file to have ms
defined on the window
. Check out this example from the library author to see an example of how this can be done.
the syntax is CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3)
for example ::
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
the above example will work if you are writting it while you are creating the table for example ::
CREATE TABLE person (
P_Id int ,
............,
............,
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);
to add this constraint to an existing table you need to follow the following syntax
ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (P_Id,LastName)
I liked the python-slugify approach here but it was stripping dots also away which was not desired. So I optimized it for uploading a clean filename to s3 this way:
pip install python-slugify
Example code:
s = 'Very / Unsafe / file\nname hähä \n\r .txt'
clean_basename = slugify(os.path.splitext(s)[0])
clean_extension = slugify(os.path.splitext(s)[1][1:])
if clean_extension:
clean_filename = '{}.{}'.format(clean_basename, clean_extension)
elif clean_basename:
clean_filename = clean_basename
else:
clean_filename = 'none' # only unclean characters
Output:
>>> clean_filename
'very-unsafe-file-name-haha.txt'
This is so failsafe, it works with filenames without extension and it even works for only unsafe characters file names (result is none
here).
You are probably manually calling setVisible(true)
on the menu. That can cause some nasty buggy behavior in the menu.
The show(Component, int x, int x)
method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where using setVisible(true)
just shows the menu without adding any additional behavior.
To make a right click popup menu simply create a JPopupMenu
.
class PopUpDemo extends JPopupMenu {
JMenuItem anItem;
public PopUpDemo() {
anItem = new JMenuItem("Click Me!");
add(anItem);
}
}
Then, all you need to do is add a custom MouseListener
to the components you would like the menu to popup for.
class PopClickListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger())
doPop(e);
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger())
doPop(e);
}
private void doPop(MouseEvent e) {
PopUpDemo menu = new PopUpDemo();
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
// Then on your component(s)
component.addMouseListener(new PopClickListener());
Of course, the tutorials have a slightly more in-depth explanation.
Note: If you notice that the popup menu is appearing way off from where the user clicked, try using the e.getXOnScreen()
and e.getYOnScreen()
methods for the x and y coordinates.
Possibly use something like firefox's tamperdata and look at the header returned (if they have publishing enabled).
The package names in Jackson 2.x got changed to com.fasterxml
1 from org.codehaus
2. So if you just need ObjectMapper, I think Jackson 1.X can satisfy with your needs.
public static URL getFinalURL(URL url) {
try {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(false);
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.addRequestProperty("Referer", "https://www.google.com/");
con.connect();
//con.getInputStream();
int resCode = con.getResponseCode();
if (resCode == HttpURLConnection.HTTP_SEE_OTHER
|| resCode == HttpURLConnection.HTTP_MOVED_PERM
|| resCode == HttpURLConnection.HTTP_MOVED_TEMP) {
String Location = con.getHeaderField("Location");
if (Location.startsWith("/")) {
Location = url.getProtocol() + "://" + url.getHost() + Location;
}
return getFinalURL(new URL(Location));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return url;
}
To get "User-Agent" and "Referer" by yourself, just go to developer mode of one of your installed browser (E.g. press F12 on Google Chrome). Then go to tab 'Network' and then click on one of the requests. You should see it's details. Just press 'Headers' sub tab (the image below)
try {
string path = args[0];
FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);
int i;
string s = "";
while ((i = fh.ReadByte()) != -1)
s = s + (char)i;
//its for reading number of paragraphs
int count = 0;
for (int j = 0; j < s.Length - 1; j++) {
if (s.Substring(j, 1) == "\n")
count++;
}
Console.WriteLine("The total searches were :" + count);
fh.Close();
} catch(Exception ex) {
Console.WriteLine(ex.Message);
}
I think you would like to learn ajax
first, try this: Ajax Tutorial
If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest
:
var xhr = new XMLHttpReuqest();
xhr.open("GET", "http://some.com");
xhr.onreadystatechange = handler; // do something here...
xhr.send();
.venv/bin/pip freeze
worked for me in bash.
The syntax (<<<
) and the command used (echo
) is wrong.
Correct would be:
#!/bin/bash
kernel="2.6.39"
distro="xyz"
cat >/etc/myconfig.conf <<EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4 line
...
EOL
cat /etc/myconfig.conf
This construction is referred to as a Here Document and can be found in the Bash man pages under man --pager='less -p "\s*Here Documents"' bash
.
This works
@interface RGBComponents : NSObject {
float components[8];
}
@property(readonly) float * components;
- (float *) components {
return components;
}
In Visual Studio Professional or Enterprise you can enable CodeLens by doing this:
Tools ? Options ? Text Editor ? All Languages ? CodeLens
This is not available in the Community Edition
Trying to give you a brief answer to your doubt, if you execute the skip(n).take(m)
methods on linq (with SQL 2005 / 2008 as database server) your query will be using the Select ROW_NUMBER() Over ...
statement, with is somehow direct paging in the SQL engine.
Giving you an example, I have a db table called mtcity
and I wrote the following query (work as well with linq to entities):
using (DataClasses1DataContext c = new DataClasses1DataContext())
{
var query = (from MtCity2 c1 in c.MtCity2s
select c1).Skip(3).Take(3);
//Doing something with the query.
}
The resulting query will be:
SELECT [t1].[CodCity],
[t1].[CodCountry],
[t1].[CodRegion],
[t1].[Name],
[t1].[Code]
FROM (
SELECT ROW_NUMBER() OVER (
ORDER BY [t0].[CodCity],
[t0].[CodCountry],
[t0].[CodRegion],
[t0].[Name],
[t0].[Code]) AS [ROW_NUMBER],
[t0].[CodCity],
[t0].[CodCountry],
[t0].[CodRegion],
[t0].[Name],
[t0].[Code]
FROM [dbo].[MtCity] AS [t0]
) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]
Which is a windowed data access (pretty cool, btw cuz will be returning data since the very begining and will access the table as long as the conditions are met). This will be very similar to:
With CityEntities As
(
Select ROW_NUMBER() Over (Order By CodCity) As Row,
CodCity //here is only accessed by the Index as CodCity is the primary
From dbo.mtcity
)
Select [t0].[CodCity],
[t0].[CodCountry],
[t0].[CodRegion],
[t0].[Name],
[t0].[Code]
From CityEntities c
Inner Join dbo.MtCity t0 on c.CodCity = t0.CodCity
Where c.Row Between @p0 + 1 AND @p0 + @p1
Order By c.Row Asc
With the exception that, this second query will be executed faster than the linq result because it will be using exclusively the index to create the data access window; this means, if you need some filtering, the filtering should be (or must be) in the Entity listing (where the row is created) and some indexes should be created as well to keep up the good performance.
Now, whats better?
If you have pretty much solid workflow in your logic, implementing the proper SQL way will be complicated. In that case LINQ will be the solution.
If you can lower that part of the logic directly to SQL (in a stored procedure), it will be even better because you can implement the second query I showed you (using indexes) and allow SQL to generate and store the Execution Plan of the query (improving performance).
It's currently working, I've just changed the operator >
in order to work in the snippet, take a look:
window.onload = function() {_x000D_
_x000D_
if (window.location.href.indexOf("test") <= -1) {_x000D_
var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
search_span[0].style.color = "blue";_x000D_
search_span[0].style.fontWeight = "bold";_x000D_
search_span[0].style.fontSize = "40px";_x000D_
_x000D_
}_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
@Aqib Mumtaz - I got it working by following the instructions in Parris' note above entitled "Adding libxml2 in Xcode 4.3 / 5 / 6". The step in using a Framework Search Path does not work and the compiler complains. Big kudos to that fella anyway!
I am using Xcode 6.2b3
Regardless of the version of Xcode you are using, it is buggy. Don't always assume that compile errors are real. There are many times when it does not follow header search paths and includes clearly listed are not found. Worse, the errors that result tend to point you in different directions so you waste a lot of time dinking around with distractions. With that said...
Recommend baby steps by starting with this exactly...:
Notes:
hope this helps.
If you happen to be developing something for Veterans, oh say an iPhone / iPad or Mac app, and are working against something called "MDWS" or "VIA" which are SOAP based interfaces to the medical record system... please contact me
Use this command:
egrep -lRZ "\.jpg|\.png|\.gif" . \
| xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
egrep
: find matching lines using extended regular expressions
-l
: only list matching filenames
-R
: search recursively through all given directories
-Z
: use \0
as record separator
"\.jpg|\.png|\.gif"
: match one of the strings ".jpg"
, ".gif"
or ".png"
.
: start the search in the current directory
xargs
: execute a command with the stdin as argument
-0
: use \0
as record separator. This is important to match the -Z
of egrep
and to avoid being fooled by spaces and newlines in input filenames.
-l
: use one line per command as parameter
sed
: the stream editor
-i
: replace the input file with the output without making a backup
-e
: use the following argument as expression
's/\.jpg\|\.gif\|\.png/.bmp/g'
: replace all occurrences of the strings ".jpg"
, ".gif"
or ".png"
with ".bmp"
The best way to think about 'null' is to recall how the similar concept is used in databases, where it indicates that a field contains "no value at all."
This is a very useful technique for writing programs that are more-easily debugged. An 'undefined' variable might be the result of a bug ... (how would you know?) ... but if the variable contains the value 'null,' you know that "someone, somewhere in this program, set it to 'null.'" Therefore, I suggest that, when you need to get rid of the value of a variable, don't "delete" ... set it to 'null.' The old value will be orphaned and soon will be garbage-collected; the new value is, "there is no value (now)." In both cases, the variable's state is certain: "it obviously, deliberately, got that way."
The reason that this is happening is because the stack panel measures every child element with positive infinity as the constraint for the axis that it is stacking elements along. The child controls have to return how big they want to be (positive infinity is not a valid return from the MeasureOverride in either axis) so they return the smallest size where everything will fit. They have no way of knowing how much space they really have to fill.
If your view doesn’t need to have a scrolling feature and the answer above doesn't suit your needs, I would suggest implement your own panel. You can probably derive straight from StackPanel and then all you will need to do is change the ArrangeOverride method so that it divides the remaining space up between its child elements (giving them each the same amount of extra space). Elements should render fine if they are given more space than they wanted, but if you give them less you will start to see glitches.
If you want to be able to scroll the whole thing then I am afraid things will be quite a bit more difficult, because the ScrollViewer gives you an infinite amount of space to work with which will put you in the same position as the child elements were originally. In this situation you might want to create a new property on your new panel which lets you specify the viewport size, you should be able to bind this to the ScrollViewer’s size. Ideally you would implement IScrollInfo, but that starts to get complicated if you are going to implement all of it properly.
It's too late to answer for this question. But if someone is searching for this answer now I've made it to run with no errors.
First of all make sure to download and add maven to path. [ mvn --version
] will give you version specifications of it if you have added to the path correctly.
Now , add following code to the maven project [ pom.xml
] , in the following code replace with your own main file entry point for eg [ com.example.test.Test ].
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>
your_package_to_class_that_contains_main_file .MainFileName</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
Now go to the command line [CMD
] in your project and type mvn package
and it will generate a jar file as something like ProjectName-0.0.1-SNAPSHOT.jar
under target
directory.
Now navigate to the target directory by cd target
.
Finally type java -jar jar-file-name.jar
and yes this should work successfully if you don't have any errors in your program.
Noticed mine worked on chrome. Got it to work in Firefox
by going to <about:config>
and setting full-screen-api.allow-trusted-requests-only
to false
.
After full screen worked once, I could set that back to true, and full screen still worked which was quite perplexing.
Kill is definitly the wrong way! The PID will stay, Replicationsjobs will be killed etc. etc.
STOP MySQL Server
/sbin/service mysql stop
START MySQL Server
/sbin/service mysql start
RESTART MySQL Server
/sbin/service mysql restart
Perhaps sudo will be needed if you have not enough rights
You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/
(very rough example)
#!/usr/bin/expect
set pass "mysecret"
spawn /usr/bin/passwd
expect "password: "
send "$pass"
expect "password: "
send "$pass"
The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true
along with start:start, end:end
in the second createReadStream
arg.
The other part of the solution was to limit the max chunksize
being sent in the response. The other answer set end
like so:
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).
I needed this stream to be closed because I was displaying the <video>
element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.
My solution was just to set a maxChunk
configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.
// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
end = start + maxChunk - 1;
chunksize = (end - start) + 1;
}
This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.
I also wrote a separate StackOverflow question and answer covering this issue.
I'm just posting this since Chrome changes alot, and none of the answers were quite up to date.
If you don't want hexagons, you can use numpy's histogram2d
function:
import numpy as np
import numpy.random
import matplotlib.pyplot as plt
# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)
heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.clf()
plt.imshow(heatmap.T, extent=extent, origin='lower')
plt.show()
This makes a 50x50 heatmap. If you want, say, 512x384, you can put bins=(512, 384)
in the call to histogram2d
.
Example:
If you were using Solr's default or Lucene query parser, you can pretty much always put it into a query string query:
POST test/_search
{
"query": {
"query_string": {
"query": "(( name:(+foo +bar) OR info:(+foo +bar) )) AND state:(1) AND (has_image:(0) OR has_image:(1)^100)"
}
}
}
That said, you may want to use a boolean query, like the one you already posted, or even a combination of the two.
Use command "php artisan migrate:rollback --step=1" to rollback migration to 1 step back.
For more info check the link :- https://laravel.com/docs/master/migrations#running-migrations
I faced the same problem when I renamed my repository on GitHub. I tried to push at which point I got the error
fatal: 'origin' does not appear to be a git repository
fatal: The remote end hung up unexpectedly
I had to change the URL using
git remote set-url origin ssh://[email protected]/username/newRepoName.git
After this all commands started working fine. You can check the change by using
git remote -v
In my case after successfull change it showed correct renamed repo in URL
[aniket@alok Android]$ git remote -v
origin ssh://[email protected]/aniket91/TicTacToe.git (fetch)
origin ssh://[email protected]/aniket91/TicTacToe.git (push)
POCO stands for "Plain Old CLR Object".
Simple to do:
header code...
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command Set
objMyRecordset = New ADODB.Recordset
On Error GoTo ERRORHAND
Working code...
objMyConn.ConnectionString = ConnStr
objMyConn.Open
code....
'Copy Data FROM Excel'
objMyConn.BeginTrans <-- define transactions to possible be rolled back
For NewRows = 2 To Rows
objMyRecordset.AddNew
For NewColumns = 0 To Columns - 1
objMyRecordset.Fields(NewColumns).Value = ActiveSheet.Cells(NewRows, NewColumns + 1)
Next NewColumns objMyRecordset.Update Next NewRows
objMyConn.CommitTrans <- if success, commit them to DB
objMyConn.Close
ERRORHAND:
Success = False
objMyConn.RollbackTrans <-- here we roll back if error encountered somewhere
LogMessage = "ERROR writing database: " & Err.Description
...
This class method can search in array by multiple conditions:
class Stdlib_Array
{
public static function multiSearch(array $array, array $pairs)
{
$found = array();
foreach ($array as $aKey => $aVal) {
$coincidences = 0;
foreach ($pairs as $pKey => $pVal) {
if (array_key_exists($pKey, $aVal) && $aVal[$pKey] == $pVal) {
$coincidences++;
}
}
if ($coincidences == count($pairs)) {
$found[$aKey] = $aVal;
}
}
return $found;
}
}
// Example:
$data = array(
array('foo' => 'test4', 'bar' => 'baz'),
array('foo' => 'test', 'bar' => 'baz'),
array('foo' => 'test1', 'bar' => 'baz3'),
array('foo' => 'test', 'bar' => 'baz'),
array('foo' => 'test', 'bar' => 'baz4'),
array('foo' => 'test4', 'bar' => 'baz1'),
array('foo' => 'test', 'bar' => 'baz1'),
array('foo' => 'test3', 'bar' => 'baz2'),
array('foo' => 'test', 'bar' => 'baz'),
array('foo' => 'test', 'bar' => 'baz'),
array('foo' => 'test4', 'bar' => 'baz1')
);
$result = Stdlib_Array::multiSearch($data, array('foo' => 'test4', 'bar' => 'baz1'));
var_dump($result);
Will produce:
array(2) {
[5]=>
array(2) {
["foo"]=>
string(5) "test4"
["bar"]=>
string(4) "baz1"
}
[10]=>
array(2) {
["foo"]=>
string(5) "test4"
["bar"]=>
string(4) "baz1"
}
}
If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext
. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.
The b-list has a good introduction to context processors.
Edit (I seem to have been confused about what the actual question was):
You'll notice that password_reset
takes a named parameter called template_name
:
def password_reset(request, is_admin_site=False,
template_name='registration/password_reset_form.html',
email_template_name='registration/password_reset_email.html',
password_reset_form=PasswordResetForm,
token_generator=default_token_generator,
post_reset_redirect=None):
Check password_reset for more information.
... thus, with a urls.py like:
from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset
urlpatterns = patterns('',
(r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
...
)
django.contrib.auth.views.password_reset
will be called for URLs matching '/accounts/password/reset'
with the keyword argument template_name = 'my_templates/password_reset.html'
.
Otherwise, you don't need to provide any context as the password_reset
view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax
error and look through the stack trace find the frame with a local variable named context
. If you want to modify the context then what I said above about context processors is probably the way to go.
In summary: what do you need to do to use your own template? Provide a template_name
keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.
Guid.NewGuid()
, as it creates GUIDs as intended.
Guid.NewGuid()
creates an empty Guid
object, initializes it by calling CoCreateGuid
and returns the object.
new Guid()
merely creates an empty GUID (all zeros, I think).
I guess they had to make the constructor public as Guid
is a struct
.
One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:
test_json = { "a": 1, "b": 2}
Once you do this, adding a json element only involves the following line:
test_json["c"] = 3
This will result in:
{'a': 1, 'b': 2, 'c': 3}
Afterwards, you can add that json back into an array or a list of that is desired.
List(1,2,3) :+ 4
Results in List[Int] = List(1, 2, 3, 4)
Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).
I asked @Alan Moore in a comment to the accepted solution how strings with newlines could be handled. He suggested using DOTALL.
Using his suggestion I created a small sample of how that works:
public void regexDotAllExample() throws UnsupportedEncodingException {
final String input = "The\nquick\nbrown\r\nfox\rjumps";
final String regex = "(?<=\\G.{4})";
Pattern splitByLengthPattern;
String[] split;
splitByLengthPattern = Pattern.compile(regex);
split = splitByLengthPattern.split(input);
System.out.println("---- Without DOTALL ----");
for (int i = 0; i < split.length; i++) {
byte[] s = split[i].getBytes("utf-8");
System.out.println("[Idx: "+i+", length: "+s.length+"] - " + s);
}
/* Output is a single entry longer than the desired split size:
---- Without DOTALL ----
[Idx: 0, length: 26] - [B@17cdc4a5
*/
//DOTALL suggested in Alan Moores comment on SO: https://stackoverflow.com/a/3761521/1237974
splitByLengthPattern = Pattern.compile(regex, Pattern.DOTALL);
split = splitByLengthPattern.split(input);
System.out.println("---- With DOTALL ----");
for (int i = 0; i < split.length; i++) {
byte[] s = split[i].getBytes("utf-8");
System.out.println("[Idx: "+i+", length: "+s.length+"] - " + s);
}
/* Output is as desired 7 entries with each entry having a max length of 4:
---- With DOTALL ----
[Idx: 0, length: 4] - [B@77b22abc
[Idx: 1, length: 4] - [B@5213da08
[Idx: 2, length: 4] - [B@154f6d51
[Idx: 3, length: 4] - [B@1191ebc5
[Idx: 4, length: 4] - [B@30ddb86
[Idx: 5, length: 4] - [B@2c73bfb
[Idx: 6, length: 2] - [B@6632dd29
*/
}
But I like @Jon Skeets solution in https://stackoverflow.com/a/3760193/1237974 also. For maintainability in larger projects where not everyone are equally experienced in Regular expressions I would probably use Jons solution.
What you can also do is to use apt-get:
apt-get install python3-pip
In my experience this works pretty fluent too, plus you get all the benefits from apt-get.
Your key selectors are incorrect. They should take an object of the type of the table in question and return the key to use in the join. I think you mean this:
var query = database.Posts.Join(database.Post_Metas,
post => post.ID,
meta => meta.Post_ID,
(post, meta) => new { Post = post, Meta = meta });
You can apply the where clause afterwards, not as part of the key selector.
The console
object is available in Internet Explorer 8 or newer, but only if you open the Developer Tools window by pressing F12 or via the menu.
It stays available even if you close the Developer Tools window again until you close your IE.
Chorme and Opera always have an available console
, at least in the current versions. Firefox has a console
when using Firebug, but it may also provide one without Firebug.
In any case it is a save approach to make the use of console
output optional. Here are some examples on how to do that:
if (console) {
console.log('Hello World!');
}
if (console) console.debug('value of someVar: ' + someVar);
For sdata
:
gsub(", ","",toString(sdata))
For a vector of integers:
gsub(", ","",toString(c(1:10)))
I had this error today with Amazon Cloudfront. It was because the cname I used (e.g cdn.example.com) was not added to the distribution settings under "alternate cnames", I only had cdn.example.com forwarded to the cloudfront domain in my site/hosting control panel, but you need to add it to Amazon CloudFront panel too.
I just tested this and it works fine
var d = new Date(1441121836000);
The data object has a constructor which takes milliseconds as an argument.
The chosen answer works very well. I'm posting my solution for anyone looking for shorter alternatives that still addresses sourcing, executing, full paths, relative paths, and symlinks. Finally, this will work on macOS, given that it cannot be assumed that GNU's coreutils' version of readlink is available.
The gotcha is that it's not using Bash, but it is easy to use in a Bash script. While the OP did not place any constraints on the language of the solution, it's probably best that most have stayed within the Bash world. This is just an alternative, and possibly an unpopular one.
PHP is available on macOS by default, and installed on a number of other platforms, though not necessarily by default. I realize this is a shortcoming, but I'll leave this here for any people coming from search engines, anyway.
export SOURCE_DIRECTORY="$(php -r 'echo dirname(realpath($argv[1]));' -- "${BASH_SOURCE[0]}")"
Ultimate way to do this.
ngOnInit() {
this.interPretationForm.controls.InterpretationType.valueChanges.takeWhile(()=> this.alive).subscribe(val =>{
console.log(val); // You check code. it will be executed every time value change.
})
}
%d seems to be the norm for printing integers, I never figured out why, they behave identically.
EDIT Step 1) Go to File > Project Structure > select project > go to "signing" and select your default or any keystore you want and fill all the details. In case you are not able to fill the details, hit the green '+' button. I've highlighted in the screenshot.
Step 2) VERY IMPORTANT: Goto Build Types> select your build type and select your "Signing Config". In my case, I've to select "config". Check the highlighted region.
It does apply, but it only applies to certain elements within the DOM. for example, it won't work on a table, td, or some other elements, but it will work on a <DIV> tag.
eg:
<body>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
Only tested in iOS 4.3.
A minor edit: you may be better off using overflow:scroll so two finger-scrolling does work.
The gacutil
utility is not available on client machines, and the Window SDK license forbids redistributing it to your customers. When your customer can not, will not, (and really should not) download the 300MB Windows SDK as part of your application's install process.
There is an officially supported API you (or your installer) can use to register an assembly in the global assembly cache. Microsoft's Windows Installer technology knows how to call this API for you. You would have to consult your MSI installer utility (e.g. WiX, InnoSetup) for their own syntax of how to indicate you want an assembly to be registered in the Global Assembly Cache.
But MSI, and gacutil, are doing nothing special. They simply call the same API you can call yourself. For documentation on how to register an assembly through code, see:
KB317540: DOC: Global Assembly Cache (GAC) APIs Are Not Documented in the .NET Framework Software Development Kit (SDK) Documentation
var IAssemblyCache assemblyCache;
CreateAssemblyCache(ref assemblyCache, 0);
String manifestPath = "D:\Program Files\Contoso\Frobber\Grob.dll";
FUSION_INSTALL_REFERENCE refData;
refData.cbSize = SizeOf(refData); //The size of the structure in bytes
refData.dwFlags = 0; //Reserved, must be zero
refData.guidScheme = FUSION_REFCOUNT_FILEPATH_GUID; //The assembly is referenced by an application that is represented by a file in the file system. The szIdentifier field is the path to this file.
refData.szIdentifier = "D:\Program Files\Contoso\Frobber\SuperGrob.exe"; //A unique string that identifies the application that installed the assembly
refData.szNonCannonicalData = "Super cool grobber 9000"; //A string that is only understood by the entity that adds the reference. The GAC only stores this string
//Add a new assembly to the GAC.
//The assembly must be persisted in the file system and is copied to the GAC.
assemblyCache.InstallAssembly(
IASSEMBLYCACHE_INSTALL_FLAG_FORCE_REFRESH, //The files of an existing assembly are overwritten regardless of their version number
manifestPath, //A string pointing to the dynamic-linked library (DLL) that contains the assembly manifest. Other assembly files must reside in the same directory as the DLL that contains the assembly manifest.
refData);
More documentation before the KB article is deleted:
The fields of the structure are defined as follows:
- cbSize - The size of the structure in bytes.
- dwFlags - Reserved, must be zero.
- guidScheme - The entity that adds the reference.
- szIdentifier - A unique string that identifies the application that installed the assembly.
- szNonCannonicalData - A string that is only understood by the entity that adds the reference. The GAC only stores this string.
Possible values for the guidScheme field can be one of the following:
FUSION_REFCOUNT_MSI_GUID
- The assembly is referenced by an application that has been installed by using Windows Installer. The szIdentifier field is set to MSI, and szNonCannonicalData is set to Windows Installer. This scheme must only be used by Windows Installer itself.FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID
- The assembly is referenced by an application that appears in Add/Remove Programs. The szIdentifier field is the token that is used to register the application with Add/Remove programs.FUSION_REFCOUNT_FILEPATH_GUID
- The assembly is referenced by an application that is represented by a file in the file system. The szIdentifier field is the path to this file. FUSION_REFCOUNT_OPAQUE_STRING_GUID - The assembly is referenced by an application that is only represented by an opaque string. The szIdentifier is this opaque string. The GAC does not perform existence checking for opaque references when you remove this.
I've colour coded this figure to ease the process.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
You can have full control over the figure using these commands, to complete the answer I've add also the control over the splines:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)
# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)
How about this?
Assuming you have System.Windows.Forms referenced.
var cbtnToggler = new CheckBox();
cbtnToggler.Appearance = Appearance.Button;
cbtnToggler.TextAlign = ContentAlignment.MiddleCenter;
cbtnToggler.MinimumSize = new Size(75, 25); //To prevent shrinkage!
Hope this helps ;)
If you use bootstrap then Update bootstrap css(bootstrap.min.css
) file and fonts files. I fixed my problem with this solution.
First I will check the python3
path where it lives
And then in the VS Code settings just add that path, for example:
"python.pythonPath": "/usr/local/bin/python3"
Subclass HashMap
and create a version that lower-cases the key on put
and get
(and probably the other key-oriented methods).
Or composite a HashMap
into the new class and delegate everything to the map, but translate the keys.
If you need to keep the original key you could either maintain dual maps, or store the original key along with the value.
Here's a dimensionality-independent standalone solution.
This will convert any N-dimensional array arr
of nonnegative integers to a one-hot N+1-dimensional array one_hot
, where one_hot[i_1,...,i_N,c] = 1
means arr[i_1,...,i_N] = c
. You can recover the input via np.argmax(one_hot, -1)
def expand_integer_grid(arr, n_classes):
"""
:param arr: N dim array of size i_1, ..., i_N
:param n_classes: C
:returns: one-hot N+1 dim array of size i_1, ..., i_N, C
:rtype: ndarray
"""
one_hot = np.zeros(arr.shape + (n_classes,))
axes_ranges = [range(arr.shape[i]) for i in range(arr.ndim)]
flat_grids = [_.ravel() for _ in np.meshgrid(*axes_ranges, indexing='ij')]
one_hot[flat_grids + [arr.ravel()]] = 1
assert((one_hot.sum(-1) == 1).all())
assert(np.allclose(np.argmax(one_hot, -1), arr))
return one_hot
git pull
wants you to either remove or save your current work so that the merge it triggers doesn't cause conflicts with your uncommitted work. Note that you should only need to remove/save untracked files if the changes you're pulling create files in the same locations as your local uncommitted files.
git checkout -f
git clean -fd
git stash
git stash -u
git pull
:git stash pop
This is one way I found. You can add a hidden button:
<button id="openModalButton" [hidden]="true" data-toggle="modal" data-target="#myModal">Open Modal</button>
Then use the code to "click" the button to open the modal:
document.getElementById("openModalButton").click();
This way can keep the bootstrap style of the modal and the fade in animation.
On Github, <p>
and <br/>
solves the problem.
<p>
I want to this to appear in a new line. Introduces extra line above
or
<br/>
another way
The only thing that worked for me was to use Ananconda and create a new conda env with conda create -n tensorflow python=3.5
then activate using activate tensorflow
and finally conda install -c conda-forge tensorflow
.
This works around every issue I had including ssl certs, proxy settings, and does not need admin access. It should be noted that this is not directly supported by the tensorflow team.
Use cd
in a subshell; the shorthand way to use this kind of subshell is parentheses.
(cd wherever; mycommand ...)
That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it's an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.
Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section
within your _Layout
which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
@RenderSection("Scripts",false/*required*/)
</head>
<body>
@RenderBody()
</body>
</html>
@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
<script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}
Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script>
declaration within the view.
Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.
An example:
try {
// Create temp file.
File temp = File.createTempFile("pattern", ".suffix");
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}
Errors like that are usually sent to the "standard error" stream, which you can pipe to a file or just make disappear on most commands:
grep pattern * -R -n 2>/dev/null
The fundamental misunderstanding here is in thinking that range
is a generator. It's not. In fact, it's not any kind of iterator.
You can tell this pretty easily:
>>> a = range(5)
>>> print(list(a))
[0, 1, 2, 3, 4]
>>> print(list(a))
[0, 1, 2, 3, 4]
If it were a generator, iterating it once would exhaust it:
>>> b = my_crappy_range(5)
>>> print(list(b))
[0, 1, 2, 3, 4]
>>> print(list(b))
[]
What range
actually is, is a sequence, just like a list. You can even test this:
>>> import collections.abc
>>> isinstance(a, collections.abc.Sequence)
True
This means it has to follow all the rules of being a sequence:
>>> a[3] # indexable
3
>>> len(a) # sized
5
>>> 3 in a # membership
True
>>> reversed(a) # reversible
<range_iterator at 0x101cd2360>
>>> a.index(3) # implements 'index'
3
>>> a.count(3) # implements 'count'
1
The difference between a range
and a list
is that a range
is a lazy or dynamic sequence; it doesn't remember all of its values, it just remembers its start
, stop
, and step
, and creates the values on demand on __getitem__
.
(As a side note, if you print(iter(a))
, you'll notice that range
uses the same listiterator
type as list
. How does that work? A listiterator
doesn't use anything special about list
except for the fact that it provides a C implementation of __getitem__
, so it works fine for range
too.)
Now, there's nothing that says that Sequence.__contains__
has to be constant time—in fact, for obvious examples of sequences like list
, it isn't. But there's nothing that says it can't be. And it's easier to implement range.__contains__
to just check it mathematically ((val - start) % step
, but with some extra complexity to deal with negative steps) than to actually generate and test all the values, so why shouldn't it do it the better way?
But there doesn't seem to be anything in the language that guarantees this will happen. As Ashwini Chaudhari points out, if you give it a non-integral value, instead of converting to integer and doing the mathematical test, it will fall back to iterating all the values and comparing them one by one. And just because CPython 3.2+ and PyPy 3.x versions happen to contain this optimization, and it's an obvious good idea and easy to do, there's no reason that IronPython or NewKickAssPython 3.x couldn't leave it out. (And in fact CPython 3.0-3.1 didn't include it.)
If range
actually were a generator, like my_crappy_range
, then it wouldn't make sense to test __contains__
this way, or at least the way it makes sense wouldn't be obvious. If you'd already iterated the first 3 values, is 1
still in
the generator? Should testing for 1
cause it to iterate and consume all the values up to 1
(or up to the first value >= 1
)?
$cat abs.sh
#!/bin/bash
echo "$(cd "$(dirname "$1")"; pwd -P)"
Some explanations:
"$1"
dirname "$1"
cd "$(dirname "$1");
into this relative dir pwd -P
and get absolute path. The -P
option will avoid symlinksecho
itThen run your script:
abs.sh your_file.txt
I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference. My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications. Here is main part used for signature verification:
...
var signature = Get(url); // base64_encoded signature received from server
var inputtext= "inputtext"; // this is main text signature was created for
bool result = VerifySignature(inputtext, signature);
...
private bool VerifySignature(string input, string signature)
{
var result = false;
using (var cps=new RSACryptoServiceProvider())
{
// converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
byte[] signatureBytes = Convert.FromBase64String(signature);
cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes );
}
return result;
}
It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:
unsigned int x = N;
In fact, we can create algorithms which evaluate at compile time (from Wikipedia):
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
Keep in mind that you don't want to zoom in/out UIImage. Instead try to zoom in/out the View which contains the UIImage View Controller.
I have made a solution for this problem. Take a look at my code:
@IBAction func scaleImage(sender: UIPinchGestureRecognizer) {
self.view.transform = CGAffineTransformScale(self.view.transform, sender.scale, sender.scale)
sender.scale = 1
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.blackColor()
}
N.B.: Don't forget to hook up the PinchGestureRecognizer.
In PL/SQL code, you can use: DBMS_OUTPUT.NEW_LINE;
Whether you can alias something depends on the data type. Objects, arrays, and functions will be handled by reference and aliasing is possible. Other types are essentially atomic, and the variable stores the value rather than a reference to a value.
arguments.callee is a function, and therefore you can have a reference to it and modify that shared object.
function foo() {
var self = arguments.callee;
self.myStaticVar = self.myStaticVar || 0;
self.myStaticVar++;
return self.myStaticVar;
}
Note that if in the above code you were to say self = function() {return 42;};
then self
would then refer to a different object than arguments.callee
, which remains a reference to foo
. When you have a compound object, the assignment operator replaces the reference, it does not change the referred object. With atomic values, a case like y++
is equivalent to y = y + 1
, which is assigning a 'new' integer to the variable.
I think you're running into problems because RedHat uses RPM for managing packages. Debian based systems use DEBs, which are managed with tools like apt.
As a general rule of thumb, if I have to set the value of the string more than once, or if there are any appends to the string, then it needs to be a string builder. I have seen applications that I have written in the past before learning about string builders that have had a huge memory foot print that just seems to keep growing and growing. Changing these programs to use the string builder cut down the memory usage significantly. Now I swear by the string builder.
There are 3 ways to achieve this as shown below
Method 1:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
headers: {
"Authorization": "Basic " + btoa(uName+":"+passwrd);
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 2:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName+":"+passwrd));
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 3:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
username:uName,
password:passwrd,
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Using Math.round()
will round the float to the nearest integer.
Angular 2 official documentation provides an explanation for when to unsubscribe and when it can be safely ignored. Have a look at this link:
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
Look for the paragraph with the heading Parent and children communicate via a service and then the blue box:
Notice that we capture the subscription and unsubscribe when the AstronautComponent is destroyed. This is a memory-leak guard step. There is no actual risk in this app because the lifetime of a AstronautComponent is the same as the lifetime of the app itself. That would not always be true in a more complex application.
We do not add this guard to the MissionControlComponent because, as the parent, it controls the lifetime of the MissionService.
I hope this helps you.
In sh the jobs command will list the background processes. In some cases it might be better to kill the newest process first, e.g. the older one created a shared socket. In those cases sort the PIDs in reverse order. Sometimes you want to wait moment for the jobs to write something on disk or stuff like that before they stop.
And don't kill if you don't have to!
for SIGNAL in TERM KILL; do
for CHILD in $(jobs -s|sort -r); do
kill -s $SIGNAL $CHILD
sleep $MOMENT
done
done
you can Try the following snippet:
var str = "How are you doing today?";
var res = str.split("o");
console.log("My Result:",res)
and your output like that
My Result: H,w are y,u d,ing t,day?
You could use 'corrplot' package.
d <- data.frame(x1=rnorm(10),
x2=rnorm(10),
x3=rnorm(10))
M <- cor(d) # get correlations
library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix
More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html
To download file on flask call. File name is Examples.pdf When I am hitting 127.0.0.1:5000/download it should get download.
Example:
from flask import Flask
from flask import send_file
app = Flask(__name__)
@app.route('/download')
def downloadFile ():
#For windows you need to use drive name [ex: F:/Example.pdf]
path = "/Examples.pdf"
return send_file(path, as_attachment=True)
if __name__ == '__main__':
app.run(port=5000,debug=True)
You can use zip
:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
... print x, y
...
1 a
2 b
3 c
Provided you are not using any dynamic class loaders you can search the classpath and for each entry search the directory or JAR file.
[[
is bash's improvement to the [
command. It has several enhancements that make it a better choice if you write scripts that target bash. My favorites are:
It is a syntactical feature of the shell, so it has some special behavior that [
doesn't have. You no longer have to quote variables like mad because [[
handles empty strings and strings with whitespace more intuitively. For example, with [
you have to write
if [ -f "$file" ]
to correctly handle empty strings or file names with spaces in them. With [[
the quotes are unnecessary:
if [[ -f $file ]]
Because it is a syntactical feature, it lets you use &&
and ||
operators for boolean tests and <
and >
for string comparisons. [
cannot do this because it is a regular command and &&
, ||
, <
, and >
are not passed to regular commands as command-line arguments.
It has a wonderful =~
operator for doing regular expression matches. With [
you might write
if [ "$answer" = y -o "$answer" = yes ]
With [[
you can write this as
if [[ $answer =~ ^y(es)?$ ]]
It even lets you access the captured groups which it stores in BASH_REMATCH
. For instance, ${BASH_REMATCH[1]}
would be "es" if you typed a full "yes" above.
You get pattern matching aka globbing for free. Maybe you're less strict about how to type yes. Maybe you're okay if the user types y-anything. Got you covered:
if [[ $ANSWER = y* ]]
Keep in mind that it is a bash extension, so if you are writing sh-compatible scripts then you need to stick with [
. Make sure you have the #!/bin/bash
shebang line for your script if you use double brackets.
You can declare the field as a first-class attribute of your form and just set choices dynamically:
class WaypointForm(forms.Form):
waypoints = forms.ChoiceField(choices=[])
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
self.fields['waypoints'].choices = waypoint_choices
You can also use a ModelChoiceField and set the queryset on init in a similar manner.
Starting with CMake 3.15, the correct way of achieving this would be using:
cmake --install <dir> --prefix "/usr"
The first method is the proper approach and will do what you need. However, with the inner joins, you will only select rows from Table1
if both phone numbers exist in Table2
. You may want to do a LEFT JOIN
so that all rows from Table1
are selected. If the phone numbers don't match, then the SomeOtherField
s would be null. If you want to make sure you have at least one matching phone number you could then do WHERE t2.PhoneNumber IS NOT NULL OR t3.PhoneNumber IS NOT NULL
The second method could have a problem: what happens if Table2
has both PhoneNumber1
and PhoneNumber2
? Which row will be selected? Depending on your data, foreign keys, etc. this may or may not be a problem.
If you're not beholden to setx
, you can use an alternate command line tool like pathed. There's a more comprehensive list of alternative PATH editors at https://superuser.com/questions/297947/is-there-a-convenient-way-to-edit-path-in-windows-7/655712#655712
You can also edit the registry value directly, which is what setx
does. More in this answer.
It's weird that your %PATH%
is getting truncated at 1024 characters. I thought setx
didn't have that problem. Though you should probably clean up the invalid path entries.
If you have more than one projects in your solution, then make sure that the correct project is set as the StartUp Project
. To set a particular project as the Startup Project of your solution, Right-click the project, choose Set As StartUp Project
.
After I set my StartUp Project correctly, desired break-point was reached by the thread.
In addition to the solutions posted above, having gone through the exact same problem, make sure you check your HTML. More specifically whether you've properly labelled your elements, as well as class and id selectors. You can do this either manually or through a validator (https://validator.w3.org/).
For me, I missed the equal sign next to the class (<div class someDiv>
vs <div class = "someDiv"
>, hence why no CSS property was applied.
This is the shortest I could find.
List version
public List<Integer> makeSequence(int begin, int end)
{
List<Integer> ret = new ArrayList<Integer>(++end - begin);
for (; begin < end; )
ret.add(begin++);
return ret;
}
Array Version
public int[] makeSequence(int begin, int end)
{
if(end < begin)
return null;
int[] ret = new int[++end - begin];
for (int i=0; begin < end; )
ret[i++] = begin++;
return ret;
}
One reason to use object
over iframe
is that object re-sizes the embedded content to fit the object dimensions. most notable on safari in iPhone 4s where screen width is 320px
and the html from the embedded URL may set dimensions greater.
Your compiler just tried to compile the file named foo.cc
. Upon hitting line number line
, the compiler finds:
#include "bar"
or
#include <bar>
The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar
. For an explanation of the difference between the versions of the include statement look here.
g++
has an option -I
. It lets you add include search paths to the command line. Imagine that your file bar
is in a folder named frobnicate
, relative to foo.cc
(assume you are compiling from the directory where foo.cc
is located):
g++ -Ifrobnicate foo.cc
You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I
that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.
Now imagine you have multiple version of bar
in different folders, given:
// A/bar
#include<string>
std::string which() { return "A/bar"; }
// B/bar
#include<string>
std::string which() { return "B/bar"; }
// C/bar
#include<string>
std::string which() { return "C/bar"; }
// foo.cc
#include "bar"
#include <iostream>
int main () {
std::cout << which() << std::endl;
}
The priority with #include "bar"
is leftmost:
$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar
As you see, when the compiler started looking through A/
, B/
and C/
, it stopped at the first or leftmost hit.
This is true of both forms, include <>
and incude ""
.
#include <bar>
and #include "bar"
Usually, the #include <xxx>
makes it look into system folders first, the #include "xxx"
makes it look into the current or custom folders first.
E.g.:
Imagine you have the following files in your project folder:
list
main.cc
with main.cc
:
#include "list"
....
For this, your compiler will #include
the file list
in your project folder, because it currently compiles main.cc
and there is that file list
in the current folder.
But with main.cc
:
#include <list>
....
and then g++ main.cc
, your compiler will look into the system folders first, and because <list>
is a standard header, it will #include
the file named list
that comes with your C++ platform as part of the standard library.
This is all a bit simplified, but should give you the basic idea.
<>
/""
-priorities and -I
According to the gcc-documentation, the priority for include <>
is, on a "normal Unix system", as follows:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].
The documentation also states:
You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.
To continue our #include<list> / #include"list"
example (same code):
g++ -I. main.cc
and
#include<list>
int main () { std::list<int> l; }
and indeed, the -I.
prioritizes the folder .
over the system includes and we get a compiler error.
This works. Just remove the button from the "dummy" div
if you want to keep the button.
function removeDummy() {_x000D_
var elem = document.getElementById('dummy');_x000D_
elem.parentNode.removeChild(elem);_x000D_
return false;_x000D_
}
_x000D_
#dummy {_x000D_
min-width: 200px;_x000D_
min-height: 200px;_x000D_
max-width: 200px;_x000D_
max-height: 200px;_x000D_
background-color: #fff000;_x000D_
}
_x000D_
<div id="dummy">_x000D_
<button onclick="removeDummy()">Remove</button>_x000D_
</div>
_x000D_
Split nextLine() by this delimiter:
(?=([^\"]*\"[^\"]*\")*[^\"]*$)")
.
The answer is NO you can't. Why?
Because the LDAP standard describes a LDAP-SEARCH as kind of function with 4 parameters:
You are interested in the filter. You've got a summary here (it's provided by Microsoft for Active Directory, it's from a standard). The filter is composed, in a boolean way, by expression of the type Attribute Operator Value
.
So the filter you give does not mean anything.
On the theoretical point of view there is ExtensibleMatch that allows buildind filters on the DN path, but it's not supported by Active Directory.
As far as I know, you have to use an attribute in AD to make the distinction for users in the two OUs.
It can be any existing discriminator attribute, or, for example the attribute called OU which is inherited from organizationalPerson
class. you can set it (it's not automatic, and will not be maintained if you move the users) with "staff" for some users and "vendors" for others and them use the filter:
(&(objectCategory=person)(|(ou=staff)(ou=vendors)))
Try this instead:
$journalName = str_replace(' ', '_', $journalName);
to remove white space
To retrieve environment variables in Node.JS you can use process.env.VARIABLE_NAME, but don't forget that assigning a property on process.env will implicitly convert the value to a string.
Even if your .env file defines a variable like SHOULD_SEND=false or SHOULD_SEND=0, the values will be converted to strings (“false” and “0” respectively) and not interpreted as booleans.
if (process.env.SHOULD_SEND) {
mailer.send();
} else {
console.log("this won't be reached with values like false and 0");
}
Instead, you should make explicit checks. I’ve found depending on the environment name goes a long way.
db.connect({
debug: process.env.NODE_ENV === 'development'
});
Here is my version, pretty much stuff from this thread is integrated (same counts for the test cases):
Object.defineProperty(Object.prototype, "equals", {
enumerable: false,
value: function (obj) {
var p;
if (this === obj) {
return true;
}
// some checks for native types first
// function and sring
if (typeof(this) === "function" || typeof(this) === "string" || this instanceof String) {
return this.toString() === obj.toString();
}
// number
if (this instanceof Number || typeof(this) === "number") {
if (obj instanceof Number || typeof(obj) === "number") {
return this.valueOf() === obj.valueOf();
}
return false;
}
// null.equals(null) and undefined.equals(undefined) do not inherit from the
// Object.prototype so we can return false when they are passed as obj
if (typeof(this) !== typeof(obj) || obj === null || typeof(obj) === "undefined") {
return false;
}
function sort (o) {
var result = {};
if (typeof o !== "object") {
return o;
}
Object.keys(o).sort().forEach(function (key) {
result[key] = sort(o[key]);
});
return result;
}
if (typeof(this) === "object") {
if (Array.isArray(this)) { // check on arrays
return JSON.stringify(this) === JSON.stringify(obj);
} else { // anyway objects
for (p in this) {
if (typeof(this[p]) !== typeof(obj[p])) {
return false;
}
if ((this[p] === null) !== (obj[p] === null)) {
return false;
}
switch (typeof(this[p])) {
case 'undefined':
if (typeof(obj[p]) !== 'undefined') {
return false;
}
break;
case 'object':
if (this[p] !== null
&& obj[p] !== null
&& (this[p].constructor.toString() !== obj[p].constructor.toString()
|| !this[p].equals(obj[p]))) {
return false;
}
break;
case 'function':
if (this[p].toString() !== obj[p].toString()) {
return false;
}
break;
default:
if (this[p] !== obj[p]) {
return false;
}
}
};
}
}
// at least check them with JSON
return JSON.stringify(sort(this)) === JSON.stringify(sort(obj));
}
});
Here is my TestCase:
assertFalse({}.equals(null));
assertFalse({}.equals(undefined));
assertTrue("String", "hi".equals("hi"));
assertTrue("Number", new Number(5).equals(5));
assertFalse("Number", new Number(5).equals(10));
assertFalse("Number+String", new Number(1).equals("1"));
assertTrue([].equals([]));
assertTrue([1,2].equals([1,2]));
assertFalse([1,2].equals([2,1]));
assertFalse([1,2].equals([1,2,3]));
assertTrue(new Date("2011-03-31").equals(new Date("2011-03-31")));
assertFalse(new Date("2011-03-31").equals(new Date("1970-01-01")));
assertTrue({}.equals({}));
assertTrue({a:1,b:2}.equals({a:1,b:2}));
assertTrue({a:1,b:2}.equals({b:2,a:1}));
assertFalse({a:1,b:2}.equals({a:1,b:3}));
assertTrue({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
assertFalse({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));
assertTrue("Function", (function(x){return x;}).equals(function(x){return x;}));
assertFalse("Function", (function(x){return x;}).equals(function(y){return y+2;}));
var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var j = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};
assertTrue(a.equals(b));
assertFalse(a.equals(c));
assertFalse(c.equals(d));
assertFalse(a.equals(e));
assertTrue(f.equals(g));
assertFalse(h.equals(g));
assertTrue(i.equals(j));
assertFalse(d.equals(k));
assertFalse(k.equals(l));
I don't see any answer with reference to CSS flex property, but it can be very useful too.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
You can download ChromeDriver here: https://sites.google.com/a/chromium.org/chromedriver/downloads
Then you have multiple options:
path
specify the location directly via executable_path
driver = webdriver.Chrome(executable_path='C:/path/to/chromedriver.exe')
The bold property of the font itself is read only, but the actual font property of the text box is not. You can change the font of the textbox to bold as follows:
textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);
And then back again:
textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
It's not so difficult.
You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.
Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.
This is pretty simple stuff.
You may try altering toolchain in case if for some reason you can't use gcc. Open Properties for your project (by right clicking on your project name in the Project Explorer), then C/C++ Build > Tool Chain Editor. You can change the current builder there from GNU Make Builder to CDT Internal Builder or whatever compatible you have.
I generally agree with solutions given above. Namely with:
for
-loop (2 and more lines)while
counter (3 and more lines)__nonzero__
implementation (many more lines) If one is to define an object as in #3 I would recommend implementing protocol for with keyword or apply contextlib.
Further I propose yet another solution. It is a 3 liner and is not of supreme elegance, but it uses itertools package and thus might be of an interest.
from itertools import (chain, repeat)
times = chain(repeat(True, 2), repeat(False))
while next(times):
print 'do stuff!'
In these example 2 is the number of times to iterate the loop. chain is wrapping two repeat iterators, the first being limited but the second is infinite. Remember that these are true iterator objects, hence they do not require infinite memory. Obviously this is much slower then solution #1. Unless written as a part of a function it might require a clean up for times variable.
Try change _DEBUG to NDEBUG macro definition in C++ project properties (for Release configuration) Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions
Here's my technique that adds a slight delay before the menu is closed after you stop hovering on the menu or the toggle button. The <button>
that you would normally click to display the nav menu is #nav_dropdown
.
$(function() {
var delay_close_it, nav_menu_timeout, open_it;
nav_menu_timeout = void 0;
open_it = function() {
if (nav_menu_timeout) {
clearTimeout(nav_menu_timeout);
nav_menu_timeout = null;
}
return $('.navbar .dropdown').addClass('open');
};
delay_close_it = function() {
var close_it;
close_it = function() {
return $('.navbar .dropdown').removeClass('open');
};
return nav_menu_timeout = setTimeout(close_it, 500);
};
$('body').on('mouseover', '#nav_dropdown, #nav_dropdown *', open_it).on('mouseout', '#nav_dropdown', delay_close_it);
return $('body').on('mouseover', '.navbar .dropdown .dropdown-menu', open_it).on('mouseout', '.navbar .dropdown .dropdown-menu', delay_close_it);
});
Use Hibernate.initialize()
within @Transactional
to initialize lazy objects.
start Transaction
Hibernate.initialize(entity.getAddresses());
Hibernate.initialize(entity.getPersons());
end Transaction
Now out side of the Transaction you are able to get lazy objects.
entity.getAddresses().size();
entity.getPersons().size();
In C, unlike say C++, you would need a format specifier that states the datatype of the variable you want to print-in this case %d as the data type is an integer . Try printf("%d",addNumbers(a,b));
The standard ConfigParser
normally requires access via config['section_name']['key']
, which is no fun. A little modification can deliver attribute access:
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
AttrDict
is a class derived from dict
which allows access via both dictionary keys and attribute access: that means a.x is a['x']
We can use this class in ConfigParser
:
config = configparser.ConfigParser(dict_type=AttrDict)
config.read('application.ini')
and now we get application.ini
with:
[general]
key = value
as
>>> config._sections.general.key
'value'
A useful 2D vector operation is a cross product that returns a scalar. I use it to see if two successive edges in a polygon bend left or right.
From the Chipmunk2D source:
/// 2D vector cross product analog.
/// The cross product of 2D vectors results in a 3D vector with only a z component.
/// This function returns the magnitude of the z value.
static inline cpFloat cpvcross(const cpVect v1, const cpVect v2)
{
return v1.x*v2.y - v1.y*v2.x;
}
In Java 8:
List<WorldLocation> locations = new ArrayList<>();
.getMap(locations.stream().toArray(WorldLocation[]::new));
You can do it with a separate UPDATE statement
UPDATE report.TEST target
SET is Deleted = 'Y'
WHERE NOT EXISTS (SELECT 1
FROM main.TEST source
WHERE source.ID = target.ID);
I don't know of any way to integrate this into your MERGE statement.
To find "hello" in your_string
if (your_string.indexOf('hello') > -1)
{
alert("hello found inside your_string");
}
For the alpha numeric you can use a regular expression:
You can use the strtok()
function to split a string (and specify the delimiter to use). Note that strtok()
will modify the string passed into it. If the original string is required elsewhere make a copy of it and pass the copy to strtok()
.
EDIT:
Example (note it does not handle consecutive delimiters, "JAN,,,FEB,MAR" for example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
int main()
{
char months[] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
char** tokens;
printf("months=[%s]\n\n", months);
tokens = str_split(months, ',');
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("month=[%s]\n", *(tokens + i));
free(*(tokens + i));
}
printf("\n");
free(tokens);
}
return 0;
}
Output:
$ ./main.exe
months=[JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC]
month=[JAN]
month=[FEB]
month=[MAR]
month=[APR]
month=[MAY]
month=[JUN]
month=[JUL]
month=[AUG]
month=[SEP]
month=[OCT]
month=[NOV]
month=[DEC]
It's 2020 now, use python3 consistently
I meet the same problem when I install selenium using pip3
, but run scripts using python
.
I can tell you something:
Snippet #1 is not acceptable because it's ignoring exception. (it's swallowing it like nothing happened).
So do not add catch block that do nothing or just rethrows.
Catch block should add some value. For example output message to end user or log error.
Do not use exception for normal flow program logic. For example:
e.g input validation. <- This is not valid exceptional situation, rather you should write method IsValid(myInput);
to check whether input item is valid or not.
Design code to avoid exception. For example:
int Parse(string input);
If we pass value that cannot be parsed to int, this method would throw and exception, instead of that we might write something like this:
bool TryParse(string input,out int result);
<- this method would return boolean indicating if parse was successfull.
Maybe this is little bit out of scope of this question, but I hope this will help you to make right decisions when it's about try {} catch(){}
and exceptions.
I tried this (and worked for me):
var img = 'data:image/png;base64, ...'; //place ur base64 encoded img here
document.body.style.backgroundImage = 'url(\'' + img + '\')';
ES6 syntax:
let img = 'data:image/png;base64, ...'
document.body.style.backgroundImage = `url('${img}')`
A bit better:
let setBackground = src => {
this.style.backgroundImage = `url('${src}')`
};
let node = nodeIGotFromDOM, img = imageBase64EncodedFromMyGF;
setBackground.call(node, img);
The simplest approach is probably to define one custom enum
with just one case
that has a String
attached to it:
enum MyError: ErrorType {
case runtimeError(String)
}
Or, as of Swift 4:
enum MyError: Error {
case runtimeError(String)
}
Example usage would be something like:
func someFunction() throws {
throw MyError.runtimeError("some message")
}
do {
try someFunction()
} catch MyError.runtimeError(let errorMessage) {
print(errorMessage)
}
If you wish to use existing Error
types, the most general one would be an NSError
, and you could make a factory method to create and throw one with a custom message.
I'll throw my hat in here:
(as part of a static class, as this snippet is two extensions)
//hex encoding of the hash, in uppercase.
public static string Sha1Hash (this string str)
{
byte[] data = UTF8Encoding.UTF8.GetBytes (str);
data = data.Sha1Hash ();
return BitConverter.ToString (data).Replace ("-", "");
}
// Do the actual hashing
public static byte[] Sha1Hash (this byte[] data)
{
using (SHA1Managed sha1 = new SHA1Managed ()) {
return sha1.ComputeHash (data);
}
Be aware that a lot of the really killer features are only in Enterprise Edition. Data compression and backup compression are among two of my top favorites - they give you free performance improvements right off the bat. Data compression lessens the amount of I/O you have to do, so a lot of queries speed up 20-40%. CPU use goes up, but in today's multi-core environments, we often have more CPU power but not more IO. Anyway, those are only in Enterprise.
If you're only going to use Standard Edition, then most of the improvements require changes to your application code and T-SQL code, so it's not quite as easy of a sell.
From the NumPy mailing list, here's another solution:
>>> a
array([[1, 2],
[0, 0],
[1, 0],
[0, 2],
[2, 1],
[1, 0],
[1, 0],
[0, 0],
[1, 0],
[2, 2]])
>>> a[np.lexsort(np.fliplr(a).T)]
array([[0, 0],
[0, 0],
[0, 2],
[1, 0],
[1, 0],
[1, 0],
[1, 0],
[1, 2],
[2, 1],
[2, 2]])
You need a Spinner
. Here it is an example:
spinner_1 = (Spinner) findViewById(R.id.spinner1);
spinner_1.setOnItemSelectedListener(this);
List<String> list = new ArrayList<String>();
list.add("RANJITH");
list.add("ARUN");
list.add("JEESMON");
list.add("NISAM");
list.add("SREEJITH");
list.add("SANJAY");
list.add("AKSHY");
list.add("FIROZ");
list.add("RAHUL");
list.add("ARJUN");
list.add("SAVIYO");
list.add("VISHNU");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_1.setAdapter(adapter);
spinner_2 = (Spinner) findViewById(R.id.spinner_two);
spinner_2.setOnItemSelectedListener(this);
List<String> city = new ArrayList<String>();
city.add("KASARGOD");
city.add("KANNUR");
city.add("THRISSUR");
city.add("KOZHIKODE");
city.add("TRIVANDRUM");
city.add("ERNAMKULLAM");
city.add("WAYANAD");
city.add("PALAKKAD");
city.add("ALAPUZHA");
city.add("IDUKKI");
city.add("KOTTAYAM");
city.add("PATHANAMTHITTA");
city.add("KOLLAM");
city.add("MALAPPURAM");
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, city);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_2.setAdapter(adapter2);
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "YOUR SELECTION IS : " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
Function Redim2d(ByRef Mtx As Variant, ByVal QtyColumnToAdd As Integer)
ReDim Preserve Mtx(LBound(Mtx, 1) To UBound(Mtx, 1), LBound(Mtx, 2) To UBound(Mtx, 2) + QtyColumnToAdd)
End Function
'Main Code
sub Main ()
Call Redim2d(MtxR8Strat, 1) 'Add one column
end sub
'OR
sub main2()
QtyColumnToAdd = 1 'Add one column
ReDim Preserve Mtx(LBound(Mtx, 1) To UBound(Mtx, 1), LBound(Mtx, 2) To UBound(Mtx, 2) + QtyColumnToAdd)
end sub
This is finally possible for GitHub Enterprise Cloud customers: Access control for GitHub Pages.
To enable access control on Pages, navigate to your repository settings, and click the dropdown menu to toggle between public and private visibility for your site.
An ultimate solution would be to embed a simple http server listening on your 'secret' port on loopback. Then you can substitute the matched image src URL with something like http://localhost:123/.../mypic.jpg
Swift 3
you want to download file bite by bite and show in progress view so you want to try this code
import UIKit
class ViewController: UIViewController,URLSessionDownloadDelegate,UIDocumentInteractionControllerDelegate {
@IBOutlet weak var img: UIImageView!
@IBOutlet weak var btndown: UIButton!
var urlLink: URL!
var defaultSession: URLSession!
var downloadTask: URLSessionDownloadTask!
//var backgroundSession: URLSession!
@IBOutlet weak var progress: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")
defaultSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)
progress.setProgress(0.0, animated: false)
}
func startDownloading () {
let url = URL(string: "http://publications.gbdirect.co.uk/c_book/thecbook.pdf")!
downloadTask = defaultSession.downloadTask(with: url)
downloadTask.resume()
}
@IBAction func btndown(_ sender: UIButton) {
startDownloading()
}
func showFileWithPath(path: String){
let isFileFound:Bool? = FileManager.default.fileExists(atPath: path)
if isFileFound == true{
let viewer = UIDocumentInteractionController(url: URL(fileURLWithPath: path))
viewer.delegate = self
viewer.presentPreview(animated: true)
}
}
// MARK:- URLSessionDownloadDelegate
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print(downloadTask)
print("File download succesfully")
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = FileManager()
let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/file.pdf"))
if fileManager.fileExists(atPath: destinationURLForFile.path){
showFileWithPath(path: destinationURLForFile.path)
print(destinationURLForFile.path)
}
else{
do {
try fileManager.moveItem(at: location, to: destinationURLForFile)
// show file
showFileWithPath(path: destinationURLForFile.path)
}catch{
print("An error occurred while moving file to destination url")
}
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
progress.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
downloadTask = nil
progress.setProgress(0.0, animated: true)
if (error != nil) {
print("didCompleteWithError \(error?.localizedDescription ?? "no value")")
}
else {
print("The task finished successfully")
}
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController
{
return self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
use of this code you want to download file store automatically in Document Directory in your application
this code 100% Working
$(document).ready(function() {
$('#someButton').click(function() {
var names = [];
$('#MyDiv input:checked').each(function() {
names.push(this.name);
});
// now names contains all of the names of checked checkboxes
// do something with it
});
});
Using Visual Studio 2019, I followed below steps to make the project name change successful:
Mates,
I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this
try{
foo();
}
catch (exception $e)
{
echo "$e->getMessage()";
}
function foo(){
echo "blah blah blah";
}
so php was throwing me error "call to undefined function ".
This kinda seem classic programming error but may help someone in need of clue.
Accompanying Timmay's answer, You need to do two changes-
Listen 80 --> Listen 81 (near line 58)
ServerName localhost:80 --> ServerName localhost:81 (near line 218)
I would just use table and not the form. Its done by using margin.
table {
margin: 0 auto;
}
also try using something like
table td {
padding-bottom: 5px;
}
instead of <br />
and also your input should end with />
e.g:
<input type="password" name="cpwd" />