Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.
Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation
import org.springframework.beans.factory.annotation.Value;
public interface DeadlineTypeProjection {
String getId();
// can get code and or change name of getter below
String getCode();
// Points to the code attribute of entity class
@Value(value = "#{target.code}")
String getText();
}
DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class DeadlineType {
String id;
// Use this annotation if you need to change the name of the property that is passed back from controller
// Needs to be called code to be used in Repository
@JsonProperty(value = "text")
String code;
}
Entity class
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {
@Id
private String id;
private String code;
}
Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>
import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {
List<ABDeadlineType> findAll();
List<DeadlineType> findAllDtoBy();
List<DeadlineTypeProjection> findAllProjectionBy();
}
Example Controller - accesses the repository directly to simplify code
@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {
private final ABDeadlineTypeRepository abDeadlineTypeRepository;
@Autowired
public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
this.abDeadlineTypeRepository = abDeadlineTypeRepository;
}
@GetMapping(value = "/list")
public ResponseEntity<List<ABDeadlineType>> list() {
List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
return ResponseEntity.ok(types);
}
@GetMapping(value = "/listdto")
public ResponseEntity<List<DeadlineType>> listDto() {
List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
return ResponseEntity.ok(types);
}
@GetMapping(value = "/listprojection")
public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {
List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
return ResponseEntity.ok(types);
}
}
Hope that helps
Les
There is no need to use angular http, you can get with js native functions
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
// on the first then you will return blob from response_x000D_
return await fetch(url).then(r => r.blob())_x000D_
.then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
_x000D_
return new File([blob], fileName+'.'+ blob.type.split('/')[1]) ;_x000D_
});_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
// with file reader you will transform the file in a data url file;_x000D_
var reader = new FileReader();_x000D_
reader.readAsDataURL(file);_x000D_
reader.onloadend = () => {_x000D_
_x000D_
// just putting the data url to img element_x000D_
document.querySelector('#image').src = reader.result ;_x000D_
}_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
const returnedTarget = Object.assign(target, source);
and pass empty array to target
in case complex objects this way works for me
$.extend(true, [], originalArray)
in case of array
$.extend(true, {}, originalObject)
in case of object
You may use something like this to call the handler written on click:
import { shallow } from 'enzyme'; // Mount is not required
page = <MyCoolPage />;
pageMounted = shallow(page);
// The below line will execute your click function
pageMounted.instance().yourOnClickFunction();
The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>
. The let keyword declares a template input variable that you reference within the template.
I can't guarantee that this will work for every new iPad Pro which will be released but this works pretty well as of 2019:
@media only screen and (min-width: 1024px) and (max-height: 1366px)
and (-webkit-min-device-pixel-ratio: 1.5) and (hover: none) {
/* ... */
}
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.
The best way is to create a person-component
and watch every person separately inside its own component, as shown below:
<person-component :person="person" v-for="person in people"></person-component>
Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit
to send an event upwards, containing the id
of modified person.
Vue.component('person-component', {_x000D_
props: ["person"],_x000D_
template: `_x000D_
<div class="person">_x000D_
{{person.name}}_x000D_
<input type='text' v-model='person.age'/>_x000D_
</div>`,_x000D_
watch: {_x000D_
person: {_x000D_
handler: function(newValue) {_x000D_
console.log("Person with ID:" + newValue.id + " modified")_x000D_
console.log("New age: " + newValue.age)_x000D_
},_x000D_
deep: true_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
people: [_x000D_
{id: 0, name: 'Bob', age: 27},_x000D_
{id: 1, name: 'Frank', age: 32},_x000D_
{id: 2, name: 'Joe', age: 38}_x000D_
]_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
<div id="app">_x000D_
<p>List of people:</p>_x000D_
<person-component :person="person" v-for="person in people"></person-component>_x000D_
</div>_x000D_
</body>
_x000D_
To get the moving average in pandas we can use cum_sum and then divide by count.
Here is the working example:
import pandas as pd
import numpy as np
df = pd.DataFrame({'id': range(5),
'value': range(100,600,100)})
# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']
# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()
print(df)
id value cum_sum count mov_avg rolling_mean2
0 0 100 100 1 100.0 NaN
1 1 200 300 2 150.0 150.0
2 2 300 600 3 200.0 250.0
3 3 400 1000 4 250.0 350.0
4 4 500 1500 5 300.0 450.0
As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON (p.vTreasuryId = f.RFC) COLLATE Database_Default
If you are a windows user and try to start py-script in cmd - don't forget to type python before filename.
python script.py
I have "No module named google" error if forget to type it.
This worked for me.
<table>
<tr>
<td *ngFor="#group of groups">
<h1>{{group.name}}</h1>
</td>
</tr>
</table>
This is incredibly ugly, but it also fixed the problem quickly for me. Your table needs a unique key which you will use to fix the tainted columns. In this example, the primary key is called 'id' and the broken timestamp column is called 'BadColumn'.
Select the IDs of the tainted columns.
select id from table where BadColumn='0000-00-00 00:00:00'
Collect the IDs into a comma-delimited string. Example: 1, 22, 33
. I used an external wrapper for this (a Perl script) to quickly spit them all out.
Use your list of IDs to update the old columns with a valid date (1971 through 2038).
update table set BadColumn='2000-01-01 00:00:00' where id in (1, 22, 33)
If you're using fs-extra, you can skip the JSON.stringify
part with the writeJson function:
const fsExtra = require('fs-extra');
fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})
My 2020's (or 2019) answer
import React, {Component, useRef, useLayoutEffect} from 'react';
import { useDispatch } from 'react-redux';
import { Toast, ToastBody, ToastHeader } from 'reactstrap';
import {WidgetHead} from './WidgetHead';
export const Widget = ({title, toggle, reload, children, width, name}) => {
let myself = useRef(null);
const dispatch = useDispatch();
useLayoutEffect(()=>{
if (myself.current) {
const height = myself.current.clientHeight
dispatch({type:'GRID_WIDGET_HEIGHT', widget:name, height})
}
}, [myself.current, myself.current?myself.current.clientHeight:0])
return (
<Toast innerRef={myself}>
<WidgetHead title={title}
toggle={toggle}
reload={reload} />
<ToastBody>
{children}
</ToastBody>
</Toast>
)
}
let use your imagination for what is missing here (WidgetHead), reactstrap
is something you can find on npm: replace innerRef
with ref
for a legacy dom element (say a <div>
).
The last is said to be synchronous for changes
useLayoutEffect
(or useEffect
) second argumentSecond argument is an array, and it is checked before executing the function in the first argument.
I used
[myself.current, myself.current?myself.current.clientHeight:0]
because myself.current is null before rendering, and that is a good thing not to check, the second parameter at the end myself.current.clientHeight
is what I want to check for changes.
I am solving here the problem of widget on a grid that change its height by their own will, and the grid system should be elastic enough to react ( https://github.com/STRML/react-grid-layout ).
There is no need to include a bulky library such as Moment.js to fix such a simple issue.
The issue you are facing is not with formatting, but with parsing.
As John Shammas mentions in another answer, the Date
constructor (and Date.parse
) are picky about the input. Your 2016-01-04 10:34:23
may work in one JavaScript implementation, but not necessarily in the other.
According to the specification of ECMAScript 5.1, Date.parse
supports (a simplification of) ISO 8601. That's good news, because your date is already very ISO 8601-like.
All you have to do is change the input format just a little. Swap the space for a T
: 2016-01-04T10:34:23
; and optionally add a time zone (2016-01-04T10:34:23+01:00
), otherwise UTC is assumed.
You need to provide a key.
Try doing this in your ListView Rows if you have a key property:
<TouchableHighlight key={item.key} underlayColor='#dddddd'>
If not, try just adding the item as the key:
<TouchableHighlight key={item} underlayColor='#dddddd'>
Ed Webb's answer helped in my case. And instead, you can also try add
@Rule public Mocks mocks = new Mocks(this);
if you @RunWith(JUnit4.class)
.
Run installer in command line (Admin) with argument:
vs_community_ENU.exe /uninstall /force
Then:
vs_community_ENU /CustomInstallPath E:\VisualStudio2015
You can do this very easy, look my Supervisor recipe:
- name: Setup Supervisor jobs files
template:
src: job.conf.j2
dest: "/etc/supervisor/conf.d/{{ item.job }}.conf"
owner: root
group: root
force: yes
mode: 0644
with_items:
- { job: bender, arguments: "-m 64", instances: 3 }
- { job: mailer, arguments: "-m 1024", instances: 2 }
notify: Ensure Supervisor is restarted
job.conf.j2:
[program:{{ item.job }}]
user=vagrant
command=/usr/share/nginx/vhosts/parclick.com/app/console rabbitmq:consumer {{ item.arguments }} {{ item.job }} -e prod
process_name=%(program_name)s_%(process_num)02d
numprocs={{ item.instances }}
autostart=true
autorestart=true
stderr_logfile=/var/log/supervisor/{{ item.job }}.stderr.log
stdout_logfile=/var/log/supervisor/{{ item.job }}.stdout.log
Output:
TASK [Supervisor : Setup Supervisor jobs files] ********************************
changed: [loc.parclick.com] => (item={u'instances': 3, u'job': u'bender', u'arguments': u'-m 64'})
changed: [loc.parclick.com] => (item={u'instances': 2, u'job': u'mailer', u'arguments': u'-m 1024'})
Enjoy!
Actually it is not the matter of the primarycolortext
, upgrading or downgrading the dependencies.This problem will likely occur when the version of your appcompat
library and design support library doesn't match.
Example of matching condition
compile 'com.android.support:appcompat-v7:23.1.1' // appcompat library
compile 'com.android.support:design:23.1.1' //design support library
step 1: use the command : npm install jquery --save
step 2: you can simply import angular as :
import $ from 'jquery';
that's all .
An example would be :
import { Component } from '@angular/core';
import $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(){
console.log($('body'));
}
}
For all the Windows users, try moving your codebase to a shorter windows path for eg: C:/myProj
Deeply nested Maven jar files can create a longer file path in windows. Since windows OS, by default, limits the file path length to 260 characters, it throws exception when trying to read a file located at a path that becomes more than 260 characters.
You can change this default to increase this limit to more than 260 chracters. Search around the web and you will find many posts on how to do that.
You can face similar problem while using npm packages also.
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
Postman 4.0.5 has a feature named Manage Cookies located below the Send button which manages the cookies separately from Chrome it seems.
Here's another way of doing it, add in app\Providers\AppServiceProvider.php
use Illuminate\Support\Str;
...
public function boot()
{
// add Str::currency macro
Str::macro('currency', function ($price)
{
return number_format($price, 2, '.', '\'');
});
}
Then use Str::currency() in the blade templates or directly in the Expense model.
@foreach ($Expenses as $Expense)
<tr>
<td>{{{ $Expense->type }}}</td>
<td>{{{ $Expense->narration }}}</td>
<td>{{{ Str::currency($Expense->price) }}}</td>
<td>{{{ $Expense->quantity }}}</td>
<td>{{{ Str::currency($Expense->amount) }}}</td>
</tr>
@endforeach
Put the recyclerview in any other layout (Relative layout is preferable). Then change recyclerview's height/width as match parent to that layout and set the parent layout's height/width as wrap content.
Source: This comment.
If you would like to setup the search facility inside your Fragment
, just add these few lines:
Step 1 - Add the search field to you toolbar
:
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="Search"/>
Step 2 - Add the logic to your onCreateOptionsMenu()
import android.support.v7.widget.SearchView; // not the default !
@Override
public boolean onCreateOptionsMenu( Menu menu) {
getMenuInflater().inflate( R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
searchView = (SearchView) myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// Toast like print
UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
if( ! searchView.isIconified()) {
searchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
@Override
public boolean onQueryTextChange(String s) {
// UserFeedback.show( "SearchOnQueryTextChanged: " + s);
return false;
}
});
return true;
}
Born Solutions its best one, just need a bit tweek to feet the needs, i had different responsive solutions and changed a bit
<div ng-repeat="post in posts">
<div class="vechicle-single col-lg-4 col-md-6 col-sm-12 col-xs-12">
</div>
<div class="clearfix visible-lg" ng-if="($index + 1) % 3 == 0"></div>
<div class="clearfix visible-md" ng-if="($index + 1) % 2 == 0"></div>
<div class="clearfix visible-sm" ng-if="($index + 1) % 1 == 0"></div>
<div class="clearfix visible-xs" ng-if="($index + 1) % 1 == 0"></div>
</div>
This answer is based on the solution given by Denis Nek. It solves the problem of not taking decorations like dividers into account.
public class WrappingRecyclerViewLayoutManager extends LinearLayoutManager {
public WrappingRecyclerViewLayoutManager(Context context) {
super(context, VERTICAL, false);
}
public WrappingRecyclerViewLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec, int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
Rect outRect = new Rect();
calculateItemDecorationsForChild(view, outRect);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin + outRect.bottom + outRect.top;
recycler.recycleView(view);
}
}
}
If you are using new androidx implementations, when typing Toolbar, the Studio will autocomplete it to android.support.v7.widget.Toolbar
, but you should use androidx.appcompat.widget.Toolbar
instead, otherwise you will get this error.
My problem was that embedded database was already connected. close connection
I just got the solution to this problem from a friend. he said: Add ob_start(); under your session code. You can add exit(); under the header. I tried it and it worked. Hope this helps
This is for those on a rented Hosting sever who do not have access to php.init file.
Firstly run this query
SHOW VARIABLES LIKE '%char%';
You have character_set_server='latin1'
for eg if CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
replace it to CHARSET=latin1
and remove the collate
You are good to go
Using Environment class we can get application. Properties values
@Autowired,
private Environment env;
and access using
String password =env.getProperty(your property key);
Add the below property into the web.config file for IIS sites. This worked for me on my intranet in IE11.
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="X-UA-Compatible" value="IE=edge" />
</customHeaders>
</httpProtocol>
</system.webServer>
You can use this extension I test it over
import Foundation
import UIKit
extension NSMutableAttributedString {
convenience init (fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) {
let rangeOfSubString = (fullString as NSString).range(of: subString)
let rangeOfFullString = NSRange(location: 0, length: fullString.count)//fullString.range(of: fullString)
let attributedString = NSMutableAttributedString(string:fullString)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: fullStringColor, range: rangeOfFullString)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: subStringColor, range: rangeOfSubString)
self.init(attributedString: attributedString)
}
}
This happened with me because I was using Next JS
which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window
or document
. Hence this error shows up.
Work around :
If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.
import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
ssr: false
})
export default () => <DynamicComponentWithNoSSR />
If you are using any other server side rendering library. Then add the code that you want to run at the client side in componentDidMount
. If you are using React Hooks then use useEffects
in the place of componentsDidMount
.
import React, {useState, useEffects} from 'react';
const DynamicComponentWithNoSSR = <>Some JSX</>
export default function App(){
[a,setA] = useState();
useEffect(() => {
setA(<DynamicComponentWithNoSSR/>)
});
return (<>{a}<>)
}
References :
You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Read-Host -Prompt "Press Enter to exit"
Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running. Here's the 2 registry keys that would need to be changed:
? Open With ? Windows PowerShell
When you right-click a .ps1 file and choose Open With
Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
? Run with PowerShell
When you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).
Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
You can download a .reg file from my blog to modify the registry keys for you if you don't want to do it manually.
It sounds like you likely want to use option #2. You could even wrap your whole script in a try block, and only prompt for input if an error occurred, like so:
try
{
# Do your script's stuff
}
catch
{
Write-Error $_.Exception.ToString()
Read-Host -Prompt "The above error occurred. Press Enter to exit."
}
If what you want is a fixed size array, and initialize it with nil
values, you can use an UnsafeMutableBufferPointer
, allocate memory for 64 nodes with it, and then read/write from/to the memory by subscripting the pointer type instance. This also has the benefit of avoiding checking if the memory must be reallocated, which Array
does. I would however be surprised if the compiler doesn't optimize that away for arrays that don't have any more calls to methods that may require resizing, other than at the creation site.
let count = 64
let sprites = UnsafeMutableBufferPointer<SKSpriteNode>.allocate(capacity: count)
for i in 0..<count {
sprites[i] = ...
}
for sprite in sprites {
print(sprite!)
}
sprites.deallocate()
This is however not very user friendly. So, let's make a wrapper!
class ConstantSizeArray<T>: ExpressibleByArrayLiteral {
typealias ArrayLiteralElement = T
private let memory: UnsafeMutableBufferPointer<T>
public var count: Int {
get {
return memory.count
}
}
private init(_ count: Int) {
memory = UnsafeMutableBufferPointer.allocate(capacity: count)
}
public convenience init(count: Int, repeating value: T) {
self.init(count)
memory.initialize(repeating: value)
}
public required convenience init(arrayLiteral: ArrayLiteralElement...) {
self.init(arrayLiteral.count)
memory.initialize(from: arrayLiteral)
}
deinit {
memory.deallocate()
}
public subscript(index: Int) -> T {
set(value) {
precondition((0...endIndex).contains(index))
memory[index] = value;
}
get {
precondition((0...endIndex).contains(index))
return memory[index]
}
}
}
extension ConstantSizeArray: MutableCollection {
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return count - 1
}
func index(after i: Int) -> Int {
return i + 1;
}
}
Now, this is a class, and not a structure, so there's some reference counting overhead incurred here. You can change it to a struct
instead, but because Swift doesn't provide you with an ability to use copy initializers and deinit
on structures, you'll need a deallocation method (func release() { memory.deallocate() }
), and all copied instances of the structure will reference the same memory.
Now, this class may just be good enough. Its use is simple:
let sprites = ConstantSizeArray<SKSpriteNode?>(count: 64, repeating: nil)
for i in 0..<sprites.count {
sprite[i] = ...
}
for sprite in sprites {
print(sprite!)
}
For more protocols to implement conformance to, see the Array documentation (scroll to Relationships).
window.history.pushState({urlPath:'/page1'},"",'/page1')
Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.
What you should do here is knowing to which URL you are getting redirected when you reload this page. And on that page you can get the conditions by getting the current URL and making all of your conditions.
I had a further issue that foxed me for a while when theming existing code from a CMS. I wanted to use flexbox with justify-content:space-between
but the left and right elements weren't flush.
In that system the items were floated and the container had a :before
and/or an :after
to clear floats at beginning or end. So setting those sneaky :before
and :after
elements to display:none
did the trick.
That is invalid syntax. You are mixing relational expressions with scalar operators (OR
). Specifically you cannot combine expr IN (select ...) OR (select ...)
. You probably want expr IN (select ...) OR expr IN (select ...)
. Using union would also work: expr IN (select... UNION select...)
The valid syntax with named fields:
var array = [];
@foreach (var item in model.List)
{
@:array.push({
"Project": "@item.Project",
"ProjectOrgUnit": "@item.ProjectOrgUnit"
});
}
Please explain why same ng-model
is used? And what value is passed through ng- model
and how it is passed? To be more specific, if I use console.log(color)
what would be the output?
We don't have to reinvent the wheel. Just use a library to save the time and headache.
https://github.com/dankogai/js-base64 is good and I confirm it supports unicode very well.
Base64.encode('dankogai'); // ZGFua29nYWk=
Base64.encode('???'); // 5bCP6aO85by+
Base64.encodeURI('???'); // 5bCP6aO85by-
Base64.decode('ZGFua29nYWk='); // dankogai
Base64.decode('5bCP6aO85by+'); // ???
// note .decodeURI() is unnecessary since it accepts both flavors
Base64.decode('5bCP6aO85by-'); // ???
I prefer elegant solutions
In Template
<td>Total: {{ totalSum }}</td>
In Controller
$scope.totalSum = Object.keys(cart.products).map(function(k){
return +cart.products[k].price;
}).reduce(function(a,b){ return a + b },0);
If you're using ES2015 (aka ES6)
$scope.totalSum = Object.keys(cart.products)
.map(k => +cart.products[k].price)
.reduce((a, b) => a + b);
I was facing the same issue and in my case compiler compliance level was selected as 14 in my eclipse settings. In order to fix it, I changed it to the version of JDK on my machine i.e 1.8 and recompiled the project.
I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
1.
if(1 == @$manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
2.
if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
3.
if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}
try this=> numpy.array(yourvariable) followed by the command to compare, whatever you wish to.
UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.
If your project uses Maven you can simply include UCanAccess via the following coordinates:
groupId: net.sf.ucanaccess
artifactId: ucanaccess
The following is an excerpt from pom.xml
, you may need to update the <version>
to get the most recent release:
<dependencies>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>4.0.4</version>
</dependency>
</dependencies>
As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:
UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)
Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like
ucanaccess-4.0.1.jar
/lib/
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.6.jar
All you need to do is add all five (5) JARs to your project.
NOTE: Do not add
loader/ucanload.jar
to your build path if you are adding the other five (5) JAR files. TheUcanloadDriver
class is only used in special circumstances and requires a different setup. See the related answer here for details.
Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path...
. Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this
NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.
After adding all five (5) JAR files the "Libraries" folder should look something like this:
IntelliJ IDEA: Choose File > Project Structure...
from the main menu. In the "Libraries" pane click the "Add" (+
) button and add the five (5) JAR files. Once that is done the project should look something like this:
Now "U Can Access" data in .accdb and .mdb files using code like this
// assumes...
// import java.sql.*;
Connection conn=DriverManager.getConnection(
"jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
System.out.println(rs.getString(1));
}
At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.
In my case, I had a OneToOne relation which I was using with @Column
by mistake. I changed it to @JoinColumn
and added @OneToOne
annotation and it fixed the exception.
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
Using {dplyr}:
library(dplyr)
# percentiles
infert %>%
mutate(PCT = ntile(age, 100))
# quartiles
infert %>%
mutate(PCT = ntile(age, 4))
# deciles
infert %>%
mutate(PCT = ntile(age, 10))
If you are using Pipenv
, you may need to add this to your Pipfile
:
[packages]
python-dateutil = "*"
You need to use getActivity() method from fragment for Intents.
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
getline
, as it name states, read a whole line, or at least till a delimiter that can be specified.
So the answer is "no", getline
does not match your need.
But you can do something like:
inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;
I'll not address the order of tests, sorry. Others already did it. Also, if you know about "ordered tests" - well, this is MS VS's response to the problem. I know that those ordered-tests are no fun. But they thought it will be "it" and there's really nothing more in MSTest about that.
I write about one of your assumptions:
as there is no way to tear down the static class.
Unless your static class represents some process-wide external state external to your code (like ie. the state of an unmanaged native DLL library thats P/Invoked by the rest of your code), your assumption that there is no way
is not true.
If your static class refers to this, then sorry, you are perfectly right, the rest of this anwer is irrelevant. Still, as you didn't say that, I assume your code is "managed".
Think and check the AppDomain
thingy. Rarely it is needed, but this is exactly the case when you'd probably like to use them.
You can create a new AppDomain, and instantiate the test there, and run the test method there. Static data used by managed code will isolated there and upon completion, you will be able to unload the AppDomain and all the data, statics included, will evaporate. Then, next test would initialize another appdomain, and so on.
This will work unless you have external state that you must track. AppDomains only isolate the managed memory. Any native DLL will still be load per-process and their state will be shared by all AppDomains.
Also, creating/tearing down the appdomains will, well, slow down the tests. Also, you may have problems with assembly resolution in the child appdomain, but they are solvable with reasonable amount of reusable code.
Also, you may have small problems with passing test data to - and back from - the child AppDomain. Objects passed will either have to be serializable in some way, or be MarshalByRef
or etc. Talking cross-domain is almost like IPC.
However, take care here, it will be 100% managed talking. If you take some extra care and add a little work to the AppDomain setup, you will be able to even pass delegates and run them in the target domain. Then, instead of making some hairy cross-domain setup, you can wrap your tests with to something like:
void testmethod()
{
TestAppDomainHelper.Run( () =>
{
// your test code
});
}
or even
[IsolatedAppDomain]
void testmethod()
{
// your test code
}
if your test framework supports creating such wrappers/extensions. After some initial research and work, using them is almost trivial.
you should use this code:
$json = json_encode(array_map('utf8_encode', $arr))
array_map function converts special characters in UTF8 standard
The accented Latin range \u00C0-\u017F
was not quite enough for my database of names, so I extended the regex to
[a-zA-Z\u00C0-\u024F]
[a-zA-Z\u00C0-\u024F\u1E00-\u1EFF] // includes even more Latin chars
I added these code blocks (\u00C0-\u024F
includes three adjacent blocks at once):
\u00C0-\u00FF
Latin-1 Supplement\u0100-\u017F
Latin Extended-A\u0180-\u024F
Latin Extended-B\u1E00-\u1EFF
Latin Extended AdditionalNote that \u00C0-\u00FF
is actually only a part of Latin-1 Supplement. It skips unprintable control signals and all symbols except for the awkwardly-placed multiply × \u00D7
and divide ÷ \u00F7
.
[a-zA-Z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F] // exclude ×÷
If you need more code points, you can find more ranges on Wikipedia's List of Unicode characters. For example, you could also add Latin Extended-C, D, and E, but I left them out because only historians seem interested in them now, and the D and E sets don't even render correctly in my browser.
The original regex stopping at \u017F
borked on the name "?enol". According to FontSpace's Unicode Analyzer, that first character is \u0218
, LATIN CAPITAL LETTER S WITH COMMA BELOW. (Yeah, it's usually spelled with a cedilla-S \u015E
, "Senol." But I'm not flying to Turkey to go tell him, "You're spelling your name wrong!")
if the database is maintained by you then simply create a new database and import the data from the old one. the collation problem is solved!!!!!
This would also work I believe:
$('#results').on('click', '.item', function () {
var NestId = $(this).data('id');
var url = '@Html.Raw(Url.Action("Artists", new { NestId = @NestId }))';
window.location.href = url;
})
Here you can find a good example of how to format Y-Axis value.
Also, you can use scaleLabel : "<%=value%>"
that you mentioned, It basically means that everything between <%=
and %>
tags will be treated as javascript code (i.e you can use if
statments...)
Or do apply
:
df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))
Demo:
>>> df['col1']=df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))
>>> df
col1 col2
0 w a
1 1 2
2 2 NaN
>>>
Java date libraries are notoriously broken. I would advise to use Joda Time. It will take care of leap year, time zone and so on for you.
Minimal working example:
import java.util.Scanner;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class DateTestCase {
public static void main(String[] args) {
System.out.print("Insert first date: ");
Scanner s = new Scanner(System.in);
String firstdate = s.nextLine();
System.out.print("Insert second date: ");
String seconddate = s.nextLine();
// Formatter
DateTimeFormatter dateStringFormat = DateTimeFormat
.forPattern("dd MM yyyy");
DateTime firstTime = dateStringFormat.parseDateTime(firstdate);
DateTime secondTime = dateStringFormat.parseDateTime(seconddate);
int days = Days.daysBetween(new LocalDate(firstTime),
new LocalDate(secondTime)).getDays();
System.out.println("Days between the two dates " + days);
}
}
SQL Server has a PIVOT command that might be what you are looking for.
select * from Tag
pivot (MAX(Value) for TagID in ([A1],[A2],[A3],[A4])) as TagTime;
If the columns are not constant, you'll have to combine this with some dynamic SQL.
DECLARE @columns AS VARCHAR(MAX);
DECLARE @sql AS VARCHAR(MAX);
select @columns = substring((Select DISTINCT ',' + QUOTENAME(TagID) FROM Tag FOR XML PATH ('')),2, 1000);
SELECT @sql =
'SELECT *
FROM TAG
PIVOT
(
MAX(Value)
FOR TagID IN( ' + @columns + ' )) as TagTime;';
execute(@sql);
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
As mentioned in a previous post,
rename
android:name="com.fragment.NavigationDrawerFragment"
to
class = "com.fragment.NavigationDrawerFragment"
Still, it did not work for me. I then just used the Class Name without the com.fragment part and voila it worked. So change it finally to
class = "NavigationDrawerFragment"
Just read the whole file into a StringBuilder, then split the String by dot following a space. You will get a String array.
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));
StringBuilder sb = new Stringbuilder();
while(inFile1.hasNext()) {
sb.append(inFile1.nextLine());
}
String[] yourArray = sb.toString().split(", ");
I have make an addition to @AbraCadaver answers. I have included a javascript script which will delete php starting and closing tag. We will have clean more pretty dump.
May be somebody like this too.
function dd($data){
highlight_string("<?php\n " . var_export($data, true) . "?>");
echo '<script>document.getElementsByTagName("code")[0].getElementsByTagName("span")[1].remove() ;document.getElementsByTagName("code")[0].getElementsByTagName("span")[document.getElementsByTagName("code")[0].getElementsByTagName("span").length - 1].remove() ; </script>';
die();
}
Result before:
Result After:
Now we don't have php starting and closing tag
Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.
import java.sql.*;
public class UserLogin
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection Succesfull");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
it looks like your custom JpaRepository method name does not match any Variable in your entity classs. Make sure your method name matches a variable in your entity class
for example: you got a variable name called "active" and your custom JpaRepository method says "findByActiveStatus" and since there is no variable called "activeStatus" it will throw"PropertyReferenceException"
In my case, setting SQL Server Database Engine service startup account to NT AUTHORITY\NETWORK SERVICE failed, but setting it to NT Authority\System allowed me to succesfully install my SQL Server 2016 STD instance.
Just check the following snapshot.
For further details, check @Shanky's answer at https://dba.stackexchange.com/a/71798/66179
Remember: you can avoid server rebooting using setup's SkipRules switch:
setup.exe /ACTION=INSTALL /SkipRules=RebootRequiredCheck
setup.exe /ACTION=UNINSTALL /SkipRules=RebootRequiredCheck
Follow the given steps in order to setup it up to use MySQL database:
1) Install MySQL Database Connector :
sudo apt-get install libmysqlclient-dev
2) Install the mysqlclient library :
pip install mysqlclient
3) Install MySQL server, with the following command :
sudo apt-get install mysql-server
4) Create the Database :
i) Verify that the MySQL service is running:
systemctl status mysql.service
ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :
mysql -u db_user -p
iii) CREATE DATABASE db_name;
iv) Exit MySQL server, press CTRL + D.
5) Add the MySQL Database Connection to your Application:
i) Navigate to the settings.py file and replace the current DATABASES lines with the following:
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': '/etc/mysql/my.cnf',
},
}
}
...
ii) Next, let’s edit the config file so that it has your MySQL credentials. Use vi as sudo to edit the file and add the following information:
sudo vi /etc/mysql/my.cnf
database = db_name
user = db_user
password = db_password
default-character-set = utf8
6) Once the file has been edited, we need to restart MySQL for the changes to take effect :
systemctl daemon-reload
systemctl restart mysql
7) Test MySQL Connection to Application:
python manage.py runserver your-server-ip:8000
catch (Exception ex) { ... }
WILL catch RuntimeException.
Whatever you put in catch block will be caught as well as the subclasses of it.
Create site/includes/.htaccess
file and add this line:
Deny from all
\n
That means a new line is printed.
As a side note there is no need to write that extra line . There is an built in inbuilt function there.
println() //prints the content in new line
Install prerequisites VMware Tools for LinuxOS:
If you have RHEL/CentOS:
yum install perl gcc make kernel-headers kernel-devel -y
If you have Ubuntu/Debian:
sudo apt-get -y install linux-headers-server build-essential
Extracted from: http://www.sysadmit.com/2016/01/vmware-tools-linux-instalar-requisitos.html
it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.
the thing you have to do is to change your insertion query as below
INSERT INTO `abuses` ( `user_id` , `abuser_username` , `comment` , `reg_date` , `auction_id` )
VALUES ( 100020, 'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;
Nested if's in Excel Are ugly:
=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))
That should cover it.
Not able to understand your actual problem but your case statement is incorrect
CASE
WHEN
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END
AS
COL4
You can use this
var fs = require('fs');
var myCss = {
style : fs.readFileSync('./style.css','utf8');
};
app.get('/', function(req, res){
res.render('index.ejs', {
title: 'My Site',
myCss: myCss
});
});
put this on template
<%- myCss.style %>
just build style.css
<style>
body {
background-color: #D8D8D8;
color: #444;
}
</style>
I try this for some custom css. It works for me
@model AdventureWork.CRUD.WebApp4.Models.EmployeeViewModel
@{
ViewBag.Title = "Detalle";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Ingresar Usuario</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonType, labelText: "Tipo de Persona", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.PersonType, new List<SelectListItem>
{
new SelectListItem{ Text= "SC", Value = "SC" },
new SelectListItem{ Text= "VC", Value = "VC" },
new SelectListItem{ Text= "IN", Value = "IN" },
new SelectListItem{ Text= "EM", Value = "EM" },
new SelectListItem{ Text= "SP", Value = "SP" },
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.PersonType, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeGender, labelText: "Genero", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.EmployeeGender, new List<SelectListItem>
{
new SelectListItem{ Text= "Masculino", Value = "M" },
new SelectListItem{ Text= "Femenino", Value = "F" }
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.EmployeeGender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonTitle, labelText: "Titulo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonFirstName, labelText: "Primer Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonFirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonFirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonMiddleName, labelText: "Segundo Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonMiddleName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonMiddleName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonLastName, labelText: "Apellido", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonLastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonLastName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonSuffix, labelText: "Sufijo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonSuffix, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonSuffix, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.DepartmentID, labelText: "Departamento", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.DepartmentID, new SelectList(Model.ListDepartment, "DepartmentID", "DepartmentName"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.DepartmentID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeMaritalStatus, labelText: "Estado Civil", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.EmployeeMaritalStatus, new List<SelectListItem>
{
new SelectListItem{ Text= "Soltero", Value = "S" },
new SelectListItem{ Text= "Casado", Value = "M" }
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.EmployeeMaritalStatus, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.ShiftId, labelText: "Turno", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.ShiftId, new SelectList(Model.ListShift, "ShiftId", "ShiftName"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.ShiftId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeLoginId, labelText: "Login", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeLoginId, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeLoginId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeNationalIDNumber, labelText: "Identificacion Nacional", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeNationalIDNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeNationalIDNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeJobTitle, labelText: "Cargo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeJobTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeJobTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeBirthDate, labelText: "Fecha Nacimiento", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeBirthDate, new { htmlAttributes = new { @class = "form-control datepicker" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeBirthDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeSalariedFlag, labelText: "Asalariado", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeSalariedFlag, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeSalariedFlag, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Guardar" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10" style="color:green">
@ViewBag.Message
</div>
<div class="col-md-offset-2 col-md-10" style="color:red">
@ViewBag.ErrorMessage
</div>
</div>
</div>
}
As per the docs select, the following piece of code worked for me.
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id"
ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>
You shouldn't be using an item defined in the Layout XML in order to create more instances of it. You should either create it in a separate XML and inflate it or create the TableRow programmaticaly. If creating them programmaticaly, should be something like this:
public void init(){
TableLayout ll = (TableLayout) findViewById(R.id.displayLinear);
for (int i = 0; i <2; i++) {
TableRow row= new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
checkBox = new CheckBox(this);
tv = new TextView(this);
addBtn = new ImageButton(this);
addBtn.setImageResource(R.drawable.add);
minusBtn = new ImageButton(this);
minusBtn.setImageResource(R.drawable.minus);
qty = new TextView(this);
checkBox.setText("hello");
qty.setText("10");
row.addView(checkBox);
row.addView(minusBtn);
row.addView(qty);
row.addView(addBtn);
ll.addView(row,i);
}
}
Fixed length problem nvarchar (include max), included text and added NULL/NOT NULL.
USE [put your database name here];
begin tran
DECLARE @collate nvarchar(100);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @max_length_str nvarchar(100);
DECLARE @is_nullable bit;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);
SET @collate = 'Latin1_General_CI_AS';
DECLARE local_table_cursor CURSOR FOR
SELECT [name]
FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1
ORDER BY [name]
OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @table
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE local_change_cursor CURSOR FOR
SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
, c.name column_name
, t.Name data_type
, col.CHARACTER_MAXIMUM_LENGTH
, c.column_id
, c.is_nullable
FROM sys.columns c
JOIN sys.types t ON c.system_type_id = t.system_type_id
JOIN INFORMATION_SCHEMA.COLUMNS col on col.COLUMN_NAME = c.name and c.object_id = OBJECT_ID(col.TABLE_NAME)
LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE c.object_id = OBJECT_ID(@table) AND (t.Name LIKE '%char%' OR t.Name LIKE '%text%')
AND c.collation_name <> @collate
ORDER BY c.column_id
OPEN local_change_cursor
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable
WHILE @@FETCH_STATUS = 0
BEGIN
set @max_length_str = @max_length
IF (@max_length = -1) SET @max_length_str = 'max'
IF (@max_length > 4000) SET @max_length_str = '4000'
BEGIN TRY
SET @sql =
CASE
WHEN @data_type like '%text%'
THEN 'ALTER TABLE ' + @table + ' ALTER COLUMN [' + @column_name + '] ' + @data_type + ' COLLATE ' + @collate + ' ' + CASE WHEN @is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
ELSE 'ALTER TABLE ' + @table + ' ALTER COLUMN [' + @column_name + '] ' + @data_type + '(' + @max_length_str + ') COLLATE ' + @collate + ' ' + CASE WHEN @is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
END
--PRINT @sql
EXEC sp_executesql @sql
END TRY
BEGIN CATCH
PRINT 'ERROR (' + @table + '): Some index or constraint rely on the column ' + @column_name + '. No conversion possible.'
--PRINT @sql
END CATCH
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable
END
CLOSE local_change_cursor
DEALLOCATE local_change_cursor
FETCH NEXT FROM local_table_cursor
INTO @table
END
CLOSE local_table_cursor
DEALLOCATE local_table_cursor
commit tran
GO
Notice : in case when you just need to change some specific collation use condition like this :
WHERE c.object_id = OBJECT_ID(@table) AND (t.Name LIKE '%char%' OR t.Name LIKE '%text%')
AND c.collation_name = 'collation to change'
e.g. NOT the : AND c.collation_name <> @collate
In my case, I had correct / specified collation of some columns and didn't want to change them.
Here's some code with a dummy geom_blank
layer,
range_act <- range(range(results$act), range(results$pred))
d <- reshape2::melt(results, id.vars = "pred")
dummy <- data.frame(pred = range_act, value = range_act,
variable = "act", stringsAsFactors=FALSE)
ggplot(d, aes(x = pred, y = value)) +
facet_wrap(~variable, scales = "free") +
geom_point(size = 2.5) +
geom_blank(data=dummy) +
theme_bw()
unicode
is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8
, latin-1
...).
Note that unicode
is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.
On the contrary str
in Python 2 is a plain sequence of bytes. It does not represent text!
You can think of unicode
as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str
.
Note: In Python 3, unicode
was renamed to str
and there is a new bytes
type for a plain sequence of bytes.
Some differences that you can see:
>>> len(u'à') # a single code point
1
>>> len('à') # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1')) # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8') # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?
Note that using str
you have a lower-level control on the single bytes of a specific encoding representation, while using unicode
you can only control at the code-point level. For example you can do:
>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù
What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text. You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.
In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good
If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?
It might not be the best way but you may type the following
=IF(sheet1!A1<>"",sheet1!A1,"")
and drag it down to the maximum number of rows you expect.
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
Try This:
<li class="{{ Request::is('Dashboard') ? 'active' : '' }}">_x000D_
<a href="{{ url('/Dashboard') }}">_x000D_
<i class="fa fa-dashboard"></i> <span>Dashboard</span>_x000D_
</a>_x000D_
</li>
_x000D_
(This explanation is only for positive numbers since it depends on the language otherwise)
Definition
The Modulus is the remainder of the euclidean division of one number by another. %
is called the modulo operation.
For instance, 9
divided by 4
equals 2
but it remains 1
. Here, 9 / 4 = 2
and 9 % 4 = 1
.
In your example: 5 divided by 7 gives 0 but it remains 5 (5 % 7 == 5
).
Calculation
The modulo operation can be calculated using this equation:
a % b = a - floor(a / b) * b
floor(a / b)
represents the number of times you can divide a
by b
floor(a / b) * b
is the amount that was successfully shared entirelya
) minus what was shared equals the remainder of the divisionApplied to the last example, this gives:
5 % 7 = 5 - floor(5 / 7) * 7 = 5
Modular Arithmetic
That said, your intuition was that it could be -2 and not 5. Actually, in modular arithmetic, -2 = 5 (mod 7)
because it exists k in Z such that 7k - 2 = 5
.
You may not have learned modular arithmetic, but you have probably used angles and know that -90° is the same as 270° because it is modulo 360. It's similar, it wraps! So take a circle, and say that it's perimeter is 7. Then you read where is 5. And if you try with 10, it should be at 3 because 10 % 7
is 3.
In springboot 2.4.1 im just added annotation @SpringBootTest
in my test, and obviously, setted spring.profiles.active = test
in my src/test/resources/application.yml
Im using @ExtendWith({SpringExtension.class})
and @ContextConfiguration(classes = {RabbitMQ.class, GenericMapToObject.class, ModelMapper.class, StringUtils.class})
for external confs
For people having a startTime
(like 12h:30:30) and a duration
(value in minutes like 120), you can guess the endTime
like so:
const startTime = '12:30:00';
const durationInMinutes = '120';
const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');
// endTime is equal to "14:30"
One of the most important thing to remember when decorating a method with async is that at least there is one await operator inside the method. In your example, I would translate it as shown below using TaskCompletionSource.
private Task<int> DoWorkAsync()
{
//create a task completion source
//the type of the result value must be the same
//as the type in the returning Task
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
Task.Run(() =>
{
int result = 1 + 2;
//set the result to TaskCompletionSource
tcs.SetResult(result);
});
//return the Task
return tcs.Task;
}
private async void DoWork()
{
int result = await DoWorkAsync();
}
curl_getinfo()
must be added before closing the curl handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
curl_close($ch);
My approach was, but I can't guarantee that this is the fastest solution.
df = pd.DataFrame(columns=["firstname", "lastname"])
df = df.append({
"firstname": "John",
"lastname": "Johny"
}, ignore_index=True)
Have a look at Hashtables
, Hashmaps
, HashSets
and so forth. They all store the hashed key as their keys. When invoking get(Object key)
the hash of the parameter is generated and lookup in the given hashes.
When not overwriting hashCode()
and the instance of the key has been changed (for example a simple string that doesn't matter at all), the hashCode()
could result in 2 different hashcodes for the same object, resulting in not finding your given key in map.get()
.
Another alternative to the accepted answer that avoids any issues with matrix multiplication:
def MSE(Y, YH):
return np.square(Y - YH).mean()
From the documents for np.square: "Return the element-wise square of the input."
sdas is being read as a variable. To input a string you need " "
This one seems to work on both Windows and Linux* (from this question):
def beep():
print("\a")
beep()
In Windows, can put at the end:
import winsound
winsound.Beep(500, 1000)
where 500 is the frequency in Herz
1000 is the duration in miliseconds
To work on Linux, you may need to do the following (from QO's comment):
Place the body of your loop after the while
and before the test. The actual body of the while
loop should be a no-op.
while
check_if_file_present
#do other stuff
(( current_time <= cutoff ))
do
:
done
Instead of the colon, you can use continue
if you find that more readable. You can also insert a command that will only run between iterations (not before first or after last), such as echo "Retrying in five seconds"; sleep 5
. Or print delimiters between values:
i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'
I changed the test to use double parentheses since you appear to be comparing integers. Inside double square brackets, comparison operators such as <=
are lexical and will give the wrong result when comparing 2 and 10, for example. Those operators don't work inside single square brackets.
Yesterday, I started to write my own way to bind data.
It's very funny to play with it.
I think it's beautiful and very useful. At least on my tests using firefox and chrome, Edge must works too. Not sure about others, but if they support Proxy, I think it will work.
https://jsfiddle.net/2ozoovne/1/
<H1>Bind Context 1</H1>
<input id='a' data-bind='data.test' placeholder='Button Text' />
<input id='b' data-bind='data.test' placeholder='Button Text' />
<input type=button id='c' data-bind='data.test' />
<H1>Bind Context 2</H1>
<input id='d' data-bind='data.otherTest' placeholder='input bind' />
<input id='e' data-bind='data.otherTest' placeholder='input bind' />
<input id='f' data-bind='data.test' placeholder='button 2 text - same var name, other context' />
<input type=button id='g' data-bind='data.test' value='click here!' />
<H1>No bind data</H1>
<input id='h' placeholder='not bound' />
<input id='i' placeholder='not bound'/>
<input type=button id='j' />
Here is the code:
(function(){
if ( ! ( 'SmartBind' in window ) ) { // never run more than once
// This hack sets a "proxy" property for HTMLInputElement.value set property
var nativeHTMLInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
var newDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
newDescriptor.set=function( value ){
if ( 'settingDomBind' in this )
return;
var hasDataBind=this.hasAttribute('data-bind');
if ( hasDataBind ) {
this.settingDomBind=true;
var dataBind=this.getAttribute('data-bind');
if ( ! this.hasAttribute('data-bind-context-id') ) {
console.error("Impossible to recover data-bind-context-id attribute", this, dataBind );
} else {
var bindContextId=this.getAttribute('data-bind-context-id');
if ( bindContextId in SmartBind.contexts ) {
var bindContext=SmartBind.contexts[bindContextId];
var dataTarget=SmartBind.getDataTarget(bindContext, dataBind);
SmartBind.setDataValue( dataTarget, value);
} else {
console.error( "Invalid data-bind-context-id attribute", this, dataBind, bindContextId );
}
}
delete this.settingDomBind;
}
nativeHTMLInputElementValue.set.bind(this)( value );
}
Object.defineProperty(HTMLInputElement.prototype, 'value', newDescriptor);
var uid= function(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
// SmartBind Functions
window.SmartBind={};
SmartBind.BindContext=function(){
var _data={};
var ctx = {
"id" : uid() /* Data Bind Context Id */
, "_data": _data /* Real data object */
, "mapDom": {} /* DOM Mapped objects */
, "mapDataTarget": {} /* Data Mapped objects */
}
SmartBind.contexts[ctx.id]=ctx;
ctx.data=new Proxy( _data, SmartBind.getProxyHandler(ctx, "data")) /* Proxy object to _data */
return ctx;
}
SmartBind.getDataTarget=function(bindContext, bindPath){
var bindedObject=
{ bindContext: bindContext
, bindPath: bindPath
};
var dataObj=bindContext;
var dataObjLevels=bindPath.split('.');
for( var i=0; i<dataObjLevels.length; i++ ) {
if ( i == dataObjLevels.length-1 ) { // last level, set value
bindedObject={ target: dataObj
, item: dataObjLevels[i]
}
} else { // digg in
if ( ! ( dataObjLevels[i] in dataObj ) ) {
console.warn("Impossible to get data target object to map bind.", bindPath, bindContext);
break;
}
dataObj=dataObj[dataObjLevels[i]];
}
}
return bindedObject ;
}
SmartBind.contexts={};
SmartBind.add=function(bindContext, domObj){
if ( typeof domObj == "undefined" ){
console.error("No DOM Object argument given ", bindContext);
return;
}
if ( ! domObj.hasAttribute('data-bind') ) {
console.warn("Object has no data-bind attribute", domObj);
return;
}
domObj.setAttribute("data-bind-context-id", bindContext.id);
var bindPath=domObj.getAttribute('data-bind');
if ( bindPath in bindContext.mapDom ) {
bindContext.mapDom[bindPath][bindContext.mapDom[bindPath].length]=domObj;
} else {
bindContext.mapDom[bindPath]=[domObj];
}
var bindTarget=SmartBind.getDataTarget(bindContext, bindPath);
bindContext.mapDataTarget[bindPath]=bindTarget;
domObj.addEventListener('input', function(){ SmartBind.setDataValue(bindTarget,this.value); } );
domObj.addEventListener('change', function(){ SmartBind.setDataValue(bindTarget, this.value); } );
}
SmartBind.setDataValue=function(bindTarget,value){
if ( ! ( 'target' in bindTarget ) ) {
var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
if ( 'target' in lBindTarget ) {
bindTarget.target=lBindTarget.target;
bindTarget.item=lBindTarget.item;
} else {
console.warn("Still can't recover the object to bind", bindTarget.bindPath );
}
}
if ( ( 'target' in bindTarget ) ) {
bindTarget.target[bindTarget.item]=value;
}
}
SmartBind.getDataValue=function(bindTarget){
if ( ! ( 'target' in bindTarget ) ) {
var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
if ( 'target' in lBindTarget ) {
bindTarget.target=lBindTarget.target;
bindTarget.item=lBindTarget.item;
} else {
console.warn("Still can't recover the object to bind", bindTarget.bindPath );
}
}
if ( ( 'target' in bindTarget ) ) {
return bindTarget.target[bindTarget.item];
}
}
SmartBind.getProxyHandler=function(bindContext, bindPath){
return {
get: function(target, name){
if ( name == '__isProxy' )
return true;
// just get the value
// console.debug("proxy get", bindPath, name, target[name]);
return target[name];
}
,
set: function(target, name, value){
target[name]=value;
bindContext.mapDataTarget[bindPath+"."+name]=value;
SmartBind.processBindToDom(bindContext, bindPath+"."+name);
// console.debug("proxy set", bindPath, name, target[name], value );
// and set all related objects with this target.name
if ( value instanceof Object) {
if ( !( name in target) || ! ( target[name].__isProxy ) ){
target[name]=new Proxy(value, SmartBind.getProxyHandler(bindContext, bindPath+'.'+name));
}
// run all tree to set proxies when necessary
var objKeys=Object.keys(value);
// console.debug("...objkeys",objKeys);
for ( var i=0; i<objKeys.length; i++ ) {
bindContext.mapDataTarget[bindPath+"."+name+"."+objKeys[i]]=target[name][objKeys[i]];
if ( typeof value[objKeys[i]] == 'undefined' || value[objKeys[i]] == null || ! ( value[objKeys[i]] instanceof Object ) || value[objKeys[i]].__isProxy )
continue;
target[name][objKeys[i]]=new Proxy( value[objKeys[i]], SmartBind.getProxyHandler(bindContext, bindPath+'.'+name+"."+objKeys[i]));
}
// TODO it can be faster than run all items
var bindKeys=Object.keys(bindContext.mapDom);
for ( var i=0; i<bindKeys.length; i++ ) {
// console.log("test...", bindKeys[i], " for ", bindPath+"."+name);
if ( bindKeys[i].startsWith(bindPath+"."+name) ) {
// console.log("its ok, lets update dom...", bindKeys[i]);
SmartBind.processBindToDom( bindContext, bindKeys[i] );
}
}
}
return true;
}
};
}
SmartBind.processBindToDom=function(bindContext, bindPath) {
var domList=bindContext.mapDom[bindPath];
if ( typeof domList != 'undefined' ) {
try {
for ( var i=0; i < domList.length ; i++){
var dataTarget=SmartBind.getDataTarget(bindContext, bindPath);
if ( 'target' in dataTarget )
domList[i].value=dataTarget.target[dataTarget.item];
else
console.warn("Could not get data target", bindContext, bindPath);
}
} catch (e){
console.warn("bind fail", bindPath, bindContext, e);
}
}
}
}
})();
Then, to set, just:
var bindContext=SmartBind.BindContext();
SmartBind.add(bindContext, document.getElementById('a'));
SmartBind.add(bindContext, document.getElementById('b'));
SmartBind.add(bindContext, document.getElementById('c'));
var bindContext2=SmartBind.BindContext();
SmartBind.add(bindContext2, document.getElementById('d'));
SmartBind.add(bindContext2, document.getElementById('e'));
SmartBind.add(bindContext2, document.getElementById('f'));
SmartBind.add(bindContext2, document.getElementById('g'));
setTimeout( function() {
document.getElementById('b').value='Via Script works too!'
}, 2000);
document.getElementById('g').addEventListener('click',function(){
bindContext2.data.test='Set by js value'
})
For now, I've just added the HTMLInputElement value bind.
Let me know if you know how to improve it.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
Since we have a virtual address space of 2^32 and each page size is 2^12, we can store (2^32/2^12) = 2^20 pages. Since each entry into this page table has an address of size 4 bytes, then we have 2^20*4 = 4MB. So the page table takes up 4MB in memory.
The following also requires the moment-duration-format plugin:
$.fn.countdown = function ( options ) {
var $target = $(this);
var defaults = {
seconds: 0,
format: 'hh:mm:ss',
stopAtZero: true
};
var settings = $.extend(defaults, options);
var eventTime = Date.now() + ( settings.seconds * 1000 );
var diffTime = eventTime - Date.now();
var duration = moment.duration( diffTime, 'milliseconds' );
var interval = 0;
$target.text( duration.format( settings.format, { trim: false }) );
var counter = setInterval(function () {
$target.text( moment.duration( duration.asSeconds() - ++interval, 'seconds' ).format( settings.format, { trim: false }) );
if( settings.stopAtZero && interval >= settings.seconds ) clearInterval( counter );
}, 1000);
};
Usage example:
$('#someDiv').countdown({
seconds: 30*60,
format: 'mm:ss'
});
But from what I see you have quite a simple error in syntax
<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>
the correct syntax would look like
<p th:text="${bean.field + '!' + bean.field}">Static content</p>
As a matter of fact, the syntax th:text="'static part' + ${bean.field}"
is equal to th:text="${'static part' + bean.field}"
.
Try it out. Even though this is probably kind of useless now after 6 months.
You can try:
public function index()
{
return View::make('pages/index', array('title' => 'Home page'));
}
For Python 2.7 (See Raymond's answer, for Python 3 equivalent):
Wanting to know whether something "is not None" is so common in python (and other OO languages), that in my Common.py (which I import to each module with "from Common import *"), I include these lines:
def exists(it):
return (it is not None)
Then to remove None elements from a list, simply do:
filter(exists, L)
I find this easier to read, than the corresponding list comprehension (which Raymond shows, as his Python 2 version).
You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI
as your collation. The one you specify in your question is explictly case sensitive.
You can see a list of collations here.
From Developers website:
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
You can communicate among fragments with the help of its Activity. You can communicate among activity and fragment using this approach.
Please check this link also.
May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20
what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",
Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11
you can follow BaseAdapter
and create your custome Xml
file and bind it with you BaseAdpter
and populate it with Listview
see here need to change xml
file as Require.
Use dict.items(); it can be as simple as following:
ship = collections.OrderedDict(ship.items())
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:
Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)
or like this:
Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)
I too had the same problem.
The solution for me was to add following in the pom.xml as suggested here.
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
You put your template in the wrong place. From the Flask docs:
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates
To keep your code DRY, and if your content comes from your model you should adopt a slightly different approach. Edit your model like so (tested in L5.8):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Comment extends Model
{
public function getShortDescriptionAttribute()
{
return Str::words($this->description, 10, '...');
}
}
?>
Then in your view :
{{ $comment->short_description }}
Here is example of using aggregation API. To complicate the case we're grouping by case-insensitive words from array property of the document.
db.articles.aggregate([
{
$match: {
keywords: { $not: {$size: 0} }
}
},
{ $unwind: "$keywords" },
{
$group: {
_id: {$toLower: '$keywords'},
count: { $sum: 1 }
}
},
{
$match: {
count: { $gte: 2 }
}
},
{ $sort : { count : -1} },
{ $limit : 100 }
]);
that give result such as
{ "_id" : "inflammation", "count" : 765 }
{ "_id" : "obesity", "count" : 641 }
{ "_id" : "epidemiology", "count" : 617 }
{ "_id" : "cancer", "count" : 604 }
{ "_id" : "breast cancer", "count" : 596 }
{ "_id" : "apoptosis", "count" : 570 }
{ "_id" : "children", "count" : 487 }
{ "_id" : "depression", "count" : 474 }
{ "_id" : "hiv", "count" : 468 }
{ "_id" : "prognosis", "count" : 428 }
It took me a hell of a long time to really get a handle on this. The key to me was in understanding that "@" is for stuff that you want evaluated in situ and passed through into the directive as a constant where "=" actually passes the object itself.
There's a nice blog post that explains this this at: http://blog.ramses.io/technical/AngularJS-the-difference-between-@-&-and-=-when-declaring-directives-using-isolate-scopes
Try this :
width:auto;
margin-right:50px;
with this code, the id will not appear on the link
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
No jQuery Needed
if (str.match(/[a-z]/i)) {
// alphabet letters found
}
I see three solutions to this:
Change the output encoding, so it will always output UTF-8. See e.g. Setting the correct encoding when piping stdout in Python, but I could not get these example to work.
Following example code makes the output aware of your target charset.
# -*- coding: utf-8 -*-
import sys
print sys.stdout.encoding
print u"Stöcker".encode(sys.stdout.encoding, errors='replace')
print u"????????".encode(sys.stdout.encoding, errors='replace')
This example properly replaces any non-printable character in my name with a question mark.
If you create a custom print function, e.g. called myprint
, using that mechanisms to encode output properly you can simply replace print with myprint
whereever necessary without making the whole code look ugly.
Reset the output encoding globally at the begin of the software:
The page http://www.macfreek.nl/memory/Encoding_of_Python_stdout has a good summary what to do to change output encoding. Especially the section "StreamWriter Wrapper around Stdout" is interesting. Essentially it says to change the I/O encoding function like this:
In Python 2:
if sys.stdout.encoding != 'cp850':
sys.stdout = codecs.getwriter('cp850')(sys.stdout, 'strict')
if sys.stderr.encoding != 'cp850':
sys.stderr = codecs.getwriter('cp850')(sys.stderr, 'strict')
In Python 3:
if sys.stdout.encoding != 'cp850':
sys.stdout = codecs.getwriter('cp850')(sys.stdout.buffer, 'strict')
if sys.stderr.encoding != 'cp850':
sys.stderr = codecs.getwriter('cp850')(sys.stderr.buffer, 'strict')
If used in CGI outputting HTML you can replace 'strict' by 'xmlcharrefreplace' to get HTML encoded tags for non-printable characters.
Feel free to modify the approaches, setting different encodings, .... Note that it still wont work to output non-specified data. So any data, input, texts must be correctly convertable into unicode:
# -*- coding: utf-8 -*-
import sys
import codecs
sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
print u"Stöcker" # works
print "Stöcker".decode("utf-8") # works
print "Stöcker" # fails
Main advantage of <jsp:include />
over <%@ include >
is:
<jsp:include />
allows to pass parameters
<jsp:include page="inclusion.jsp">
<jsp:param name="menu" value="objectValue"/>
</jsp:include>
which is not possible in <%@include file="somefile.jsp" %>
The list of encodings that node supports natively is rather short:
If you are using an older version than 6.4.0, or don't want to deal with non-Unicode encodings, you can recode the string:
Use iconv-lite to recode files:
var iconvlite = require('iconv-lite');
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
return iconvlite.decode(content, encoding);
}
Alternatively, use iconv:
var Iconv = require('iconv').Iconv;
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
var iconv = new Iconv(encoding, 'UTF-8');
var buffer = iconv.convert(content);
return buffer.toString('utf8');
}
Try this:
<!DOCTYPE html>
<html>
<body>
<p>Add Section</p>
<label>First Number:</label>
<input id="txt1" type="text"/><br />
<label>Second Number:</label>
<input id="txt2" type="text"/><br />
<input type="button" name="Add" value="Add" onclick="addTwoNumber()"/>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}
</script>
</body>
</html>
As of Go 1.4, the go generate
tool has been introduced together with the stringer
command that makes your enum easily debuggable and printable.
Why so complicated? When you can do:
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
If you need more times check out the window.performance object:
console.log(window.performance);
Will show you the timing object:
connectEnd Time when server connection is finished.
connectStart Time just before server connection begins.
domComplete Time just before document readiness completes.
domContentLoadedEventEnd Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive Time just before readiness set to interactive.
domLoading Time just before readiness set to loading.
domainLookupEnd Time after domain name lookup.
domainLookupStart Time just before domain name lookup.
fetchStart Time when the resource starts being fetched.
loadEventEnd Time when the load event is complete.
loadEventStart Time just before the load event is fired.
navigationStart Time after the previous document begins unload.
redirectCount Number of redirects since the last non-redirect.
redirectEnd Time after last redirect response ends.
redirectStart Time of fetch that initiated a redirect.
requestStart Time just before a server request.
responseEnd Time after the end of a response or connection.
responseStart Time just before the start of a response.
timing Reference to a performance timing object.
navigation Reference to performance navigation object.
performance Reference to performance object for a window.
type Type of the last non-redirect navigation event.
unloadEventEnd Time after the previous document is unloaded.
unloadEventStart Time just before the unload event is fired.
At the moment I am working "like" you, just on a lower scale, which is why I don't have a PoC for my suggestion.
However, I seem to find success in using pickle as caching system and outsourcing execution of various functions into files - executing these files from my commando / main file; For example i use a prepare_use.py to convert object types, split a data set into test, validating and prediction data set.
How does your caching with pickle work? I use strings in order to access pickle-files that are dynamically created, depending on which parameters and data sets were passed (with that i try to capture and determine if the program was already run, using .shape for data set, dict for passed parameters). Respecting these measures, i get a String to try to find and read a .pickle-file and can, if found, skip processing time in order to jump to the execution i am working on right now.
Using databases I encountered similar problems, which is why i found joy in using this solution, however - there are many constraints for sure - for example storing huge pickle sets due to redundancy. Updating a table from before to after a transformation can be done with proper indexing - validating information opens up a whole other book (I tried consolidating crawled rent data and stopped using a database after 2 hours basically - as I would have liked to jump back after every transformation process)
I hope my 2 cents help you in some way.
Greetings.
This can be massively simplified with just 1 line of code in viewDidAppear:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableViewHeightConstraint.constant = tableView.contentSize.height
}
Create unique constraint that two numbers together CANNOT together be repeated:
ALTER TABLE someTable
ADD UNIQUE (col1, col2)
Looks like the invisible character -
ALT+255
Try this
select REPLACE(ProductAlternateKey, ' ', '@')
--type ALT+255 instead of space for the second expression in REPLACE
from DimProducts
where ProductAlternateKey like '46783815%'
Raj
Edit: Based on ASCII() results, try ALT+10
- use numeric keypad
I had this in viewPager and the crash was because any fragment had to have its own tag, duplicate tags or ids for same fragment are not allowed.
... And for those who - like me - are very early in their numpy learning curve,
import numpy as np
pure = np.linspace(-1, 1, 100)
noise = np.random.normal(0, 1, 100)
signal = pure + noise
If you are interested in understand performance, the best answer is to use a profiler.
Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
You need to enable deep object dirty checking. By default angular only checks the reference of the top level variable that you watch.
App.directive('d3Visualization', function() {
return {
restrict: 'E',
scope: {
val: '='
},
link: function(scope, element, attrs) {
scope.$watch('val', function(newValue, oldValue) {
if (newValue)
console.log("I see a data change!");
}, true);
}
}
});
see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.
Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data
variable the watch the variable directly.
scope.$watch('val.children', function(newValue, oldValue) {}, true);
version 1.2.x introduced $watchCollection
Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)
scope.$watchCollection('val.children', function(newValue, oldValue) {});
Initialize empty frame with column names
import pandas as pd
col_names = ['A', 'B', 'C']
my_df = pd.DataFrame(columns = col_names)
my_df
Add a new record to a frame
my_df.loc[len(my_df)] = [2, 4, 5]
You also might want to pass a dictionary:
my_dic = {'A':2, 'B':4, 'C':5}
my_df.loc[len(my_df)] = my_dic
Append another frame to your existing frame
col_names = ['A', 'B', 'C']
my_df2 = pd.DataFrame(columns = col_names)
my_df = my_df.append(my_df2)
Performance considerations
If you are adding rows inside a loop consider performance issues. For around the first 1000 records "my_df.loc" performance is better, but it gradually becomes slower by increasing the number of records in the loop.
If you plan to do thins inside a big loop (say 10M? records or so), you are better off using a mixture of these two; fill a dataframe with iloc until the size gets around 1000, then append it to the original dataframe, and empty the temp dataframe. This would boost your performance by around 10 times.
Please read carefully
If everything is woking same as google code then please check manifest file in my case i added geo key and map key that's why exception occurs,
Note - do not add two keys in manifest file remove map key
meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/google_maps_key"/>
add this code.
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/auto_location"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
The trick is to add both max-height: 100%;
and max-width: 100%;
to .container img
. Example CSS:
.container {
width: 300px;
border: dashed blue 1px;
}
.container img {
max-height: 100%;
max-width: 100%;
}
In this way, you can vary the specified width of .container
in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)
Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/
If you're not opposed to implicit type casting I'll offer this an alternative solution. Is it more readable with better formatting? You be the judge.
DECLARE @StartDate datetime = '10/01/2012 08:40:18.000'
,@EndDate datetime = '10/04/2012 09:52:48.000'
SELECT
STR(ss/3600, 5) + ':' + RIGHT('0' + LTRIM(ss%3600/60), 2) + ':' + RIGHT('0' + LTRIM(ss%60), 2) AS [hh:mm:ss]
FROM (VALUES(DATEDIFF(s, @StartDate, @EndDate))) seconds (ss)
this works too.
df = NULL
for (k in 1:10)
{
x = 1
y = 2
z = 3
df = rbind(df, data.frame(x,y,z))
}
output will look like this
df #enter
x y z #col names
1 2 3
Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).
If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel
public class ThisViewModel : ViewModelBase
{
TypeOfAncestorViewModel Parent { get; set; }
}
and bind against that directly instead.
<TextBox Text="{Binding Parent}" />
You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.
Python script that calculates Simpsons rule:
def integrate(y_vals, h):
i = 1
total = y_vals[0] + y_vals[-1]
for y in y_vals[1:-1]:
if i % 2 == 0:
total += 2 * y
else:
total += 4 * y
i += 1
return total * (h / 3.0)
h
is the offset (or gap) between y values, and y_vals
is an array of well, y values.
Example (In same file as above function):
y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)
Or
Navigate to project root folder and use following commands :
mvn clean install -U or mvn clean install --update-snapshots
Here -U will Forces a check for missing releases and updated snapshots on remote repositories
wt = tt - cpu tm.
Tt = cpu tm + wt.
Where wt
is a waiting time and tt
is turnaround time. Cpu time is also called burst time.
Edit 2018-05-28 I have changed the example to use Java 8's Time API:
LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();
Since you're using SQL Server 2008, you have the geography
data type available, which is designed for exactly this kind of data:
DECLARE @source geography = 'POINT(0 51.5)'
DECLARE @target geography = 'POINT(-3 56)'
SELECT @source.STDistance(@target)
Gives
----------------------
538404.100197555
(1 row(s) affected)
Telling us it is about 538 km from (near) London to (near) Edinburgh.
Naturally there will be an amount of learning to do first, but once you know it it's far far easier than implementing your own Haversine calculation; plus you get a LOT of functionality.
If you want to retain your existing data structure, you can still use STDistance
, by constructing suitable geography
instances using the Point
method:
DECLARE @orig_lat DECIMAL(12, 9)
DECLARE @orig_lng DECIMAL(12, 9)
SET @orig_lat=53.381538 set @orig_lng=-1.463526
DECLARE @orig geography = geography::Point(@orig_lat, @orig_lng, 4326);
SELECT *,
@orig.STDistance(geography::Point(dest.Latitude, dest.Longitude, 4326))
AS distance
--INTO #includeDistances
FROM #orig dest
You can do this more easy way. And 100% works that you want
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your database password
$dbname = "demo"; //your database name
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
$query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Massive Electronics</title>
<script type="text/javascript" src="loder.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date_time','Tempout'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
}
?>
]);
var options = {
title: 'Date_time Vs Room Out Temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>
loder.js link here loder.js
It seems that you can't do all this in a trigger. According to the documentation:
Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.
According to this answer, it seems that you should:
create a stored procedure, that inserts into/Updates the target table, then updates the other row(s), all in a transaction.
With a stored proc you'll manually commit the changes (insert and update). I haven't done this in MySQL, but this post looks like a good example.
I tried this DB insert method, but as it does not use the model, it ignored a sluggable trait I had on the model. So, given the Model for this table exists, as soon as its migrated, I figured the model would be available to use to insert data. And I came up with this:
public function up() {
Schema::create('parent_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->timestamps();
});
ParentCategory::create(
[
'id' => 1,
'name' => 'Occasions',
],
);
}
This worked correctly, and also took into account the sluggable trait on my Model to automatically generate a slug for this entry, and uses the timestamps too. NB. Adding the ID was no neccesary, however, I wanted specific IDs for my categories in this example. Tested working on Laravel 5.8
do a dir /s /b > out.txt
and then add a guide at position 260
In powershell cmd /c dir /s /b |? {$_.length -gt 260}
See http://angular-ui.github.io/bootstrap/#/collapse
function CollapseDemoCtrl($scope) {
$scope.isCollapsed = false;
}
<div ng-controller="CollapseDemoCtrl">
<button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
<hr>
<div collapse="isCollapsed">
<div class="well well-large">Some content</div>
</div>
</div>
I suggest you when working with listview or recyclerview to use SwipeRefreshLayout. Like this
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/card_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
Only wrap your view and this will create an animation of refresh when loading data or by swipping down the screen as we can do in many apps.
Here's the documentation of how to use it:
https://developer.android.com/training/swipe/add-swipe-interface.html
https://developer.android.com/training/swipe/respond-refresh-request.html
Happy coding !
UTF-8 is not a character set, it's an encoding. The character set for UTF-8 is Unicode. If you want to store Unicode text you use the nvarchar
data type.
If the database would use UTF-8 to store text, you would still not get the text out as encoded UTF-8 data, you would get it out as decoded text.
You can easily store UTF-8 encoded text in the database, but then you don't store it as text, you store it as binary data (varbinary
).
Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed()
function:
var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?
to get the items checked you can use CheckedItems
or GetItemsChecked
. I tried below code in .NET 4.5
Iterate through the CheckedItems
collection. This will give you the item number in the list of checked items, not the overall list. So if the first item in the list is not checked and the second item is checked, the code below will display text like Checked Item 1 = MyListItem2
.
//Determine if there are any items checked.
if(chBoxListTables.CheckedItems.Count != 0)
{
//looped through all checked items and show results.
string s = "";
for (int x = 0; x < chBoxListTables.CheckedItems.Count; x++)
{
s = s + (x + 1).ToString() + " = " + chBoxListTables.CheckedItems[x].ToString()+ ", ";
}
MessageBox.Show(s);//show result
}
-OR-
Step through the Items collection and call the GetItemChecked
method for each item. This will give you the item number in the overall list, so if the first item in the list is not checked and the second item is checked, it will display something like Item 2 = MyListItem2
.
int i;
string s;
s = "Checked items:\n" ;
for (i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
s = s + "Item " + (i+1).ToString() + " = " + checkedListBox1.Items[i].ToString() + "\n";
}
}
MessageBox.Show (s);
Hope this helps...
In case you would like to find the area between 2 values of x mean = 1; standard deviation = 2; the probability of x between [0.5,2]
import scipy.stats
scipy.stats.norm(1, 2).cdf(2) - scipy.stats.norm(1,2).cdf(0.5)
The first parameter to LayoutParams is the width and the second is the height. So if you want the width to be FILL_PARENT, but the width to be, say, 20px, then use something new LayoutParams(FILL_PARENT, 20). Of course you should never use actual pixels in your code; you'll need to conver that to density-independent pixels, but you get the idea. Also, you need to make sure your parent LinearLayout has the right width and height that you're looking for. Seems to be you want the LinearLayout to fill the parent width-wise and then have the adview fill that linearlayout witdh-wise as well, so you probably need to specify android:layout_width:"fill_parent" and android:layout_height:"wrap_content" in your linear layout's xml.
var module = angular.module("example", []);
module.controller("orderByController", function ($scope) {
$scope.orderByValue = function (value) {
return value;
};
$scope.items = ["c", "b", "a"];
$scope.objList = [
{
"name": "c"
}, {
"name": "b"
}, {
"name": "a"
}];
$scope.item = "b";
});
Use:
c._ctkk=eval('((function(){var a\x3d2143197373;var b\x3d-58933561;return 408631+\x27.\x27+(a+b)})())');
<script type="text/javascript">
(function(){
var d="text/javascript",e="text/css",f="stylesheet",g="script",h="link",k="head",l="complete",m="UTF-8",n=".";
function p(b){
var a=document.getElementsByTagName(k)[0];
a||(a=document.body.parentNode.appendChild(document.createElement(k)));
a.appendChild(b)}
function _loadJs(b){
var a=document.createElement(g);
a.type=d;
a.charset=m;
a.src=b;
p(a)}
function _loadCss(b){
var a=document.createElement(h);
a.type=e;
a.rel=f;
a.charset=m;
a.href=b;
p(a)}
function _isNS(b){
b=b.split(n);
for(var a=window,c=0;c<b.length;++c)
if(!(a=a[b[c]])) return ! 1;
return ! 0}
function _setupNS(b){
b=b.split(n);
for(var a=window,c=0;c<b.length;++c)
a.hasOwnProperty?a.hasOwnProperty(b[c])?a=a[b[c]]:a=a[b[c]]={}:a=a[b[c]]||(a[b[c]]={});
return a}
window.addEventListener&&"undefined"==typeof document.readyState&&window.addEventListener("DOMContentLoaded",function(){document.readyState=l},!1);
if (_isNS('google.translate.Element')){return}
(function(){
var c=_setupNS('google.translate._const');
c._cl='en';
c._cuc='googleTranslateElementInit1';
c._cac='';
c._cam='';
c._ctkk=eval('((function(){var a\x3d2143197373;var b\x3d-58933561;return 408631+\x27.\x27+(a+b)})())');
var h='translate.googleapis.com';
var s=(true?'https':window.location.protocol=='https:'?'https':'http')+'://';
var b=s+h;
c._pah=h;
c._pas=s;
c._pbi=b+'/translate_static/img/te_bk.gif';
c._pci=b+'/translate_static/img/te_ctrl3.gif';
c._pli=b+'/translate_static/img/loading.gif';
c._plla=h+'/translate_a/l';
c._pmi=b+'/translate_static/img/mini_google.png';
c._ps=b+'/translate_static/css/translateelement.css';
c._puh='translate.google.com';
_loadCss(c._ps);
_loadJs(b+'/translate_static/js/element/main.js');
})();
})();
</script>
Set your PRIMARY KEY as AUTO_INCREMENT.
There is several escaping options with same result:
body { width: ~"calc(100% - 250px - 1.5em)"; }
body { width: calc(~"100% - 250px - 1.5em"); }
body { width: calc(100% ~"-" 250px ~"-" 1.5em); }
In handlebar version 3.0 onwards,
{{#each users as |user userId|}}
Id: {{userId}} Name: {{user.name}}
{{/each}}
In this particular example, user will have the same value as the current context and userId will have the index value for the iteration. Refer - http://handlebarsjs.com/block_helpers.html in block helpers section
I don't know if I understand your question, but maybe:
foreach ($_POST as $id=>$value)
if (strncmp($id,'id[',3) $info[rtrim(ltrim($id,'id['),']')]=$_POST[$id];
would help
That is if you really want to have a different name (id[key]) on each checkbox of the html form (not very efficient). If not you can just name them all the same, i.e. 'id' and iterate on the (selected) values of the array, like: foreach ($_POST['id'] as $key=>$value)...
In Ronald's example, if the date formats are different (as displayed below) then modify the format
parameter
survey <- data.frame(date=c("2012-07-26","2012-07-25"),tx_start=c("2012-01-01","2012-01-01"))
survey$date_diff <- as.Date(as.character(survey$date), format="%Y-%m-%d")-
as.Date(as.character(survey$tx_start), format="%Y-%m-%d")
survey:
date tx_start date_diff
1 2012-07-26 2012-01-01 207 days
2 2012-07-25 2012-01-01 206 days
DECLARE @test nvarchar(100)
SET @test = 'Foreign Tax Credit - 1997'
SELECT @test, left(@test, charindex('-', @test) - 2) AS LeftString,
right(@test, len(@test) - charindex('-', @test) - 1) AS RightString
I've posted here some methods to convert interval to nanoseconds and nanoseconds to interval. These methods have a nanosecond precision.
You just need to adjust it to get milliseconds instead of nanoseconds.
A shorter method to convert interval to nanoseconds.
SELECT (EXTRACT(DAY FROM (
INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval --Maximum value: INTERVAL '+694444 10:39:59.999999999' DAY(6) TO SECOND(9) or up to 3871 year
) * 24 * 60) * 60 + EXTRACT(SECOND FROM (
INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval
))) * 100 AS MILLIS FROM DUAL;
MILLIS
1598434427263.027
If you are using System.Windows.Point
data type to represent a point, you can use
// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distance = Point.Subtract(p2, p1).Length;
Update 2017-01-08:
Point.Subtract
is System.Windows.Vector and it has also property LengthSquared
to save one sqrt
calculation if you just need to compare distance.WindowsBase
assembly may be needed in your projectExample with LengthSquared
and operators
// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distanceSquared = (p2 - p1).LengthSquared;
On Bootstrap5
Like noticed in the docu you can use the "data-bs-parent=.." attribute
If parent is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior - this is dependent on the card class). The attribute has to be set on the target collapsible area.
This should work for you
public class MyActivity extends Activity {
protected ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateTable();
}
private void populateTable() {
mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
new Thread() {
@Override
public void run() {
doLongOperation();
try {
// code runs in a thread
runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressDialog.dismiss();
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
}.start();
}
/** fake operation for testing purpose */
protected void doLongOperation() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
}
}
Set the system to console, following the previous suggestions. Only, also had to change the character set to Unicode, see the snapshot of Visual Studio 2015 above.
Here is a solution that may help with this strange behaviour. I couldn't find a better solution than place a button to manually trigger the change event.
EDIT: Maybe a custom binding like this could help:
ko.bindingHandlers.changeSelectValue = {
init: function(element,valueAccessor){
$(element).change(function(){
var value = $(element).val();
if($(element).is(":focus")){
//Do whatever you want with the new value
}
});
}
};
And in your select data-bind attribute add:
changeSelectValue: yourSelectValue
Latest versions of Excel has a new tool called Slicers. Using slicers in VBA is actually more reliable that .CurrentPage (there have been reports of bugs while looping through numerous filter options). Here is a simple example of how you can select a slicer item (remember to deselect all the non-relevant slicer values):
Sub Step_Thru_SlicerItems2()
Dim slItem As SlicerItem
Dim i As Long
Dim searchName as string
Application.ScreenUpdating = False
searchName="Value1"
For Each slItem In .VisibleSlicerItems
If slItem.Name <> .SlicerItems(1).Name Then _
slItem.Selected = False
Else
slItem.Selected = True
End if
Next slItem
End Sub
There are also services like SmartKato that would help you out with setting up your dashboards or reports and/or fix your code.
Taken from here - Introduction to Time Complexity of an Algorithm
In computer science, the time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input.
The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms. When expressed this way, the time complexity is said to be described asymptotically, i.e., as the input size goes to infinity.
For example, if the time required by an algorithm on all inputs of size n is at most 5n3 + 3n, the asymptotic time complexity is O(n3). More on that later.
Few more Examples:
An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.
Examples:
An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.
Consider the following examples, below I am linearly searching for an element, this has a time complexity of O(n).
int find = 66;
var numbers = new int[] { 33, 435, 36, 37, 43, 45, 66, 656, 2232 };
for (int i = 0; i < numbers.Length - 1; i++)
{
if(find == numbers[i])
{
return;
}
}
More Examples:
An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size.
Example: Binary Search
Recall the "twenty questions" game - the task is to guess the value of a hidden number in an interval. Each time you make a guess, you are told whether your guess is too high or too low. Twenty questions game implies a strategy that uses your guess number to halve the interval size. This is an example of the general problem-solving method known as binary search
An algorithm is said to run in quadratic time if its time execution is proportional to the square of the input size.
Examples:
So the issue I ran into was this... the application I used to grant the permissions converted the Schema.TableName into a single DB statement in the wrong table, so the grant was indeed wrong, but looked correct when we did a SHOW GRANTS FOR UserName if you weren't paying very close attention to GRANT SELECT vs GRANT TABLE SELECT. Manually correcting the Grant Select on Table w/ proper escaping of Schema
.Table
solved my issue.
May be unrelated, but I can imagine if one client does this wrong, another might too.
Hope that's helpful.
On Ubuntu 14.04 using Apache 2.4, I did the following:
Add the following in the file, apache2.conf (under /etc/apache2
):
<Directory /home/rocky/code/documentroot/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
and reload the server:
sudo service apache2 reload
Edit: This also works on OS X Yosemite with Apache 2.4. The all-important line is
Require all granted
Look at the getFragmentManager().popBackStack()
methods (there are several to choose from)
http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
Using Guava, it gets syntactically simplified:
Stats.meanOf(numericList);
You need to use the property /a
on the set command.
For example,
set /a "c=%a%+%b%"
This allows you to use arithmetic expressions in the set command, rather than simple concatenation.
Your code would then be:
@set a=3
@set b=4
@set /a "c=%a%+%b%"
echo %c%
@set /a "d=%c%+1"
echo %d%
and would output:
7
8
There seems to be a lot of bad practice being thrown around Event Handler Attributes. Bad practice is not knowing and using available features where it is most appropriate. The Event Attributes are fully W3C Documented standards and there is nothing bad practice about them. It's no different than placing inline styles, which is also W3C Documented and can be useful in times. Whether you place it wrapped in script tags or not, it's gonna be interpreted the same way.
https://www.w3.org/TR/html5/webappapis.html#event-handler-idl-attributes
Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy
file (path is as in the reply of Petey B)
permission java.io.FilePermission "your folder path", "write"
In your case it would be
permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"
Here /-
means any files or sub-folders inside this folder.
Warning: But by doing this, you are inviting some security risk.
if(!rsData.IsDBNull(rsData.GetOrdinal("usr.ursrdaystime")))
{
strLevel = rsData.GetString("usr.ursrdaystime");
}
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.isdbnull.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal.aspx
You can just concatenate the strings and build a command line.
std::string command = a + ' ' + b + " > " + c;
system(command.c_str());
You don't need any extra libraries for this.
Different approach for creating columns string
create table #temp
(
date datetime,
category varchar(3),
amount money
)
insert into #temp values ('1/1/2012', 'ABC', 1000.00)
insert into #temp values ('2/1/2012', 'DEF', 500.00)
insert into #temp values ('2/1/2012', 'GHI', 800.00)
insert into #temp values ('2/10/2012', 'DEF', 700.00)
insert into #temp values ('3/1/2012', 'ABC', 1100.00)
DECLARE @cols AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';
SELECT @cols = @cols + QUOTENAME(category) + ',' FROM (select distinct category from #temp ) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end
set @query =
'SELECT * from
(
select date, amount, category from #temp
) src
pivot
(
max(amount) for category in (' + @cols + ')
) piv'
execute(@query)
drop table #temp
Result
date ABC DEF GHI
2012-01-01 00:00:00.000 1000.00 NULL NULL
2012-02-01 00:00:00.000 NULL 500.00 800.00
2012-02-10 00:00:00.000 NULL 700.00 NULL
2012-03-01 00:00:00.000 1100.00 NULL NULL
I found a simple way to detect this :
scrollView.getViewTreeObserver()
.addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
if (scrollView.getChildAt(0).getBottom()
<= (scrollView.getHeight() + scrollView.getScrollY())) {
//scroll view is at bottom
} else {
//scroll view is not at bottom
}
}
});
This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.
topleft {
top: 0%;
left: 0%;
}
bottomright {
top: 100%;
left: 100%;
-webkit-transform: translate(-100%,-100%);
}
Couldn't you just pass the a name attribute and wrap it in a form?
<form id="form" action="do_stuff.php" method="post">
<select id="select_catalog" name="select_catalog_query">
<?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
</select>
</form>
And then look for $_POST['select_catalog_query']
?
One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.
PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.
pip install py-mini-racer
from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
return a+c+b;
}
""")
ctx.call("escramble_758")
And yes, you have to replace document.write
with return
as others suggested
Have you thought about this:
try {
ko.applyBindings(PersonListViewModel);
}
catch (err) {
console.log(err.message);
}
I came up with this because in Knockout, i found this code
var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
if (!sourceBindings) {
if (alreadyBound) {
throw Error("You cannot apply bindings multiple times to the same element.");
}
ko.utils.domData.set(node, boundElementDomDataKey, true);
}
So to me its not really an issue that its already bound, its that the error was not caught and dealt with...
Based on Saad Ahmed's answer, here is a method that can be used for any two points.
public static double calculateAngle(double x1, double y1, double x2, double y2)
{
double angle = Math.toDegrees(Math.atan2(x2 - x1, y2 - y1));
// Keep angle between 0 and 360
angle = angle + Math.ceil( -angle / 360 ) * 360;
return angle;
}
The recommended solution did not work for me, and I could live with dumping all non ascii characters, so
s = s.encode('ascii',errors='ignore')
which left me with something stripped that doesn't throw errors.
anyway you have not a unlimited accuracy so C define a constant in this way:
#define PI 3.14159265358979323846
import math.h to use this
\1
in double quotes needs to be escaped. So you want either
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1")
or
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, '\1')
see the docs on gsub where it says "If it is a double-quoted string, both back-references must be preceded by an additional backslash."
That being said, if you just want the result of the match you can do:
"Z_sdsd: sdsd".scan(/^Z_.*(?=:)/)
or
"Z_sdsd: sdsd"[/^Z_.*(?=:)/]
Note that the (?=:)
is a non-capturing group so that the :
doesn't show up in your match.
I have used this way lots time ...
@Component({_x000D_
selector: "data",_x000D_
template: "<h1>{{ getData() }}</h1>"_x000D_
})_x000D_
_x000D_
export class DataComponent{_x000D_
this.http.get(path).subscribe({_x000D_
DataComponent.setSubscribeData(res);_x000D_
})_x000D_
}_x000D_
_x000D_
_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
DataComponent.subscribeData=data;_x000D_
return data;_x000D_
}
_x000D_
use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...
All you need to do is make an array of fields and then set it to the class you want like shown below.
Field fld[] = (class name).class.getDeclaredFields();
for(Field x : fld)
{System.out.println(x);}
For example if you did
Field fld[] = Integer.class.getDeclaredFields();
for(Field x : fld)
{System.out.println(x);}
you would get
public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
static final char[] java.lang.Integer.digits
static final char[] java.lang.Integer.DigitTens
static final char[] java.lang.Integer.DigitOnes
static final int[] java.lang.Integer.sizeTable
private static java.lang.String java.lang.Integer.integerCacheHighPropValue
private final int java.lang.Integer.value
public static final int java.lang.Integer.SIZE
private static final long java.lang.Integer.serialVersionUID
I'm a python beginner, so to getter a clear idea of lambda I compared it with a 'for' loop; in terms of efficiency. Here's the code (python 2.7) -
import time
start = time.time() # Measure the time taken for execution
def first():
squares = map(lambda x: x**2, range(10))
# ^ Lambda
end = time.time()
elapsed = end - start
print elapsed + ' seconds'
return elapsed # gives 0.0 seconds
def second():
lst = []
for i in range(10):
lst.append(i**2)
# ^ a 'for' loop
end = time.time()
elapsed = end - start
print elapsed + ' seconds'
return elapsed # gives 0.0019998550415 seconds.
print abs(second() - first()) # Gives 0.0019998550415 seconds!(duh)
Use numpy. array. flatten() to convert a 2D NumPy array into a 1D array
print(array_2d)
array_1d = array_2d. flatten() flatten array_2d
print(array_1d)
@Manuel was part way there. You can add the compiler option as well, like this:
If you have CMake 3.1.0+, this becomes even easier:
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)
If you are using CMake 2.8.12+, you can simplify this to:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
Older CMake versions may require:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON)
there too.
This is called modular exponentiation(https://en.wikipedia.org/wiki/Modular_exponentiation).
Let's assume you have the following expression:
19 ^ 3 mod 7
Instead of powering 19 directly you can do the following:
(((19 mod 7) * 19) mod 7) * 19) mod 7
But this can take also a long time due to a lot of sequential multipliations and so you can multiply on squared values:
x mod N -> x ^ 2 mod N -> x ^ 4 mod -> ... x ^ 2 |log y| mod N
Modular exponentiation algorithm makes assumptions that:
x ^ y == (x ^ |y/2|) ^ 2 if y is even
x ^ y == x * ((x ^ |y/2|) ^ 2) if y is odd
And so recursive modular exponentiation algorithm will look like this in java:
/**
* Modular exponentiation algorithm
* @param x Assumption: x >= 0
* @param y Assumption: y >= 0
* @param N Assumption: N > 0
* @return x ^ y mod N
*/
public static long modExp(long x, long y, long N) {
if(y == 0)
return 1 % N;
long z = modExp(x, Math.abs(y/2), N);
if(y % 2 == 0)
return (long) ((Math.pow(z, 2)) % N);
return (long) ((x * Math.pow(z, 2)) % N);
}
Special thanks to @chux for found mistake with incorrect return value in case of y and 0 comparison.
Are the Android samples not good enough? I've found the ApiDemos to be indispensable when learning a new aspect of Android, myself.
I think if you have any data point with apostrophe you can add one apostrophe before the apostrophe
eg. 'This is John's place'
Here MYSQL assumes two sentence 'This is John' 's place'
You can put 'This is John''s place'. I think it should work that way.
It is the NextStep (= NS) heritage. NeXT was the computer company that Steve Jobs formed after he quit Apple in 1985, and NextStep was it's operating system (UNIX based) together with the Obj-C language and runtime. Together with it's libraries and tools, NextStep was later renamed OpenStep (which was also the name on an API that NeXT developed together with Sun), which in turn later became Cocoa.
These different names are actually quite confusing (especially since some of the names differs only in which characters are upper or lower case..), try this for an explanation:
I was having the same issue and I solved it doing the following:
In Visual Studio, select "Project properties".
Select the "Web" Tab.
Select "Use Local IIS Web server".
Check "Use IIS Express"
It should be noted that not only will the caret (^) behave differently within the brackets, it will have the opposite result of placing it outside of the brackets. Placing the caret where you have it will search for all strings NOT beginning with the content you placed within the brackets. You also would want to place a period before the asterisk in between your brackets as with grep, it also acts as a "wildcard".
grep ^[.rwx].*[0-9]$
This should work for you, I noticed that some posters used a character class in their expressions which is an effective method as well, but you were not using any in your original expression so I am trying to get one as close to yours as possible explaining every minor change along the way so that it is better understood. How can we learn otherwise?
I copied and pasted my connection string configuration into my test project and started running into this error. The connection string worked fine in my WebAPI project. Here is my fix.
var connection = ConfigurationManager.ConnectionStrings["MyConnectionString"];
var unitOfWork = new UnitOfWork(new SqlConnection(connection.ConnectionString));
There are very good answers in this thread, but meanwhile many of them are outdated. Using git-filter-branch
is no longer recommended, because it is difficult to use and awfully slow on big repositories.
git-filter-repo
is much faster and simpler to use.
git-filter-repo
is a Python script, available at github: https://github.com/newren/git-filter-repo . When installed it looks like a regular git command and can be called by git filter-repo
.
You need only one file: the Python3 script git-filter-repo. Copy it to a path that is included in the PATH variable. On Windows you may have to change the first line of the script (refer INSTALL.md). You need Python3 installed installed on your system, but this is not a big deal.
First you can run
git filter-repo --analyze
This helps you to determine what to do next.
You can delete your DVD-rip file everywhere:
git filter-repo --invert-paths --path-match DVD-rip
Filter-repo is really fast. A task that took around 9 hours on my computer by filter-branch, was completed in 4 minutes by filter-repo. You can do many more nice things with filter-repo. Refer to the documentation for that.
Warning: Do this on a copy of your repository. Many actions of filter-repo cannot be undone. filter-repo will change the commit hashes of all modified commits (of course) and all their descendants down to the last commits!
In my case I needed a list of prefixes
colsToScale=["production", "test", "development"]
dc[dc.columns[dc.columns.str.startswith(tuple(colsToScale))]]
On Ubuntu you can enable a cron.log
file to contain just the CRON entries.
Uncomment the line that mentions cron
in /etc/rsyslog.d/50-default.conf
file:
# Default rules for rsyslog.
#
# For more information see rsyslog.conf(5) and /etc/rsyslog.conf
#
# First some standard log files. Log by facility.
#
auth,authpriv.* /var/log/auth.log
*.*;auth,authpriv.none -/var/log/syslog
#cron.* /var/log/cron.log
Save and close the file and then restart the rsyslog
service:
sudo systemctl restart rsyslog
You can now see cron log entries in its own file:
sudo tail -f /var/log/cron.log
Sample outputs:
Jul 18 07:05:01 machine-host-name CRON[13638]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
However, you will not see more information about what scripts were actually run inside /etc/cron.daily
or /etc/cron.hourly
, unless those scripts direct output to the cron.log (or perhaps to some other log file).
If you want to verify if a crontab is running and not have to search for it in cron.log
or syslog
, create a crontab that redirects output to a log file of your choice - something like:
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
30 2 * * 1 /usr/local/sbin/certbot-auto renew >> /var/log/le-renew.log 2>&1
Steps taken from: https://www.cyberciti.biz/faq/howto-create-cron-log-file-to-log-crontab-logs-in-ubuntu-linux/
I was also getting this error, I found that it was because I had deleted the Default Application Pool "DefaultAppPool". Re-creating it fixed the problem. Drove me crazy for a few days.
This error will appear if either the web application is mapped to a non-existent app-pool; or if that application pool is stopped.
I had the same issue trying to find text in files with powershell. I used the following - to stay as close to the Linux environment as possible.
Hopefully this helps somebody:
PowerShell:
PS) new-alias grep findstr
PS) ls -r *.txt | cat | grep "some random string"
Explanation:
ls - lists all files
-r - recursively (in all files and folders and subfolders)
*.txt - only .txt files
| - pipe the (ls) results to next command (cat)
cat - show contents of files comming from (ls)
| - pipe the (cat) results to next command (grep)
grep - search contents from (cat) for "some random string" (alias to findstr)
Yes, this works as well:
PS) ls -r *.txt | cat | findstr "some random string"
I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload
instruction was immediately evaluated, and then the $
usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).
So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.
var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
console.log("script loaded :)");
onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
For my needs, it works fine now. Hope this can help others :)
Tree like structure in Notepad++ without plugin
Download Notepad++ 6.8.8 & then follow step below :
Notepad++ -> View-> Project-> choose Panel 1 OR Panel 2 OR Panel 3 ->
It will create a sub part Wokspace on the left side -> Right click on Workspace & click Add Project -> Again right click on Project which is created recently -> And click on Add Files From Directory.
This is it. Enjoy
You can actually have all the code in the aspx page. As explained here.
Sample from here:
<%@ Language=C# %>
<HTML>
<script runat="server" language="C#">
void MyButton_OnClick(Object sender, EventArgs e)
{
MyLabel.Text = MyTextbox.Text.ToString();
}
</script>
<body>
<form id="MyForm" runat="server">
<asp:textbox id="MyTextbox" text="Hello World" runat="server"></asp:textbox>
<asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick" runat="server"></asp:button>
<asp:label id="MyLabel" runat="server"></asp:label>
</form>
</body>
</HTML>
I had the same problem, but using the Run Custom Tool command as suggested by Timwi did not help in my case.
However it lead me into the right direction, because I ended up in the Properties of the .resx file. Here I noticed a difference to another .resx file that caused no problems.
In my case I had to change the property "Build Action" from "Resource" to "Embedded Resource".
My best guess for the reason is, that I had the .resx in a library that was used from another application. My application did not have its own .resx file, so it had to use the one from the library - which is only available when it's embedded in the library and not "stand alone".
As you said GWT does not support reflection. You should use deferred binding instead of reflection, or third party library such as gwt-ent for reflection suppport at gwt layer.
Use :
<EditText
..
android:drawableStart="@drawable/icon" />
you can declare a Numpy array dynamically for 1 dimension as shown below:
import numpy as np
n = 2
new_table = np.empty(shape=[n,1])
new_table[0,0] = 2
new_table[1,0] = 3
print(new_table)
The above example assumes we know we need to have 1 column but we want to allocate the number of rows dynamically (in this case the number or rows required is equal to 2)
output is shown below:
[[2.] [3.]]
@Ichorus's answer is correct for views, but if you want to draw rotated rectangles or text, you can do the following in your onDraw (or onDispatchDraw) callback for your view:
(note that theta is the angle from the x axis of the desired rotation, pivot is the Point that represents the point around which we want the rectangle to rotate, and horizontalRect is the rect's position "before" it was rotated)
canvas.save();
canvas.rotate(theta, pivot.x, pivot.y);
canvas.drawRect(horizontalRect, paint);
canvas.restore();
use this code this might help you to get tab like behaviour when user presses enter
Private Sub TxtSearch_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TxtSearch.KeyPress
Try
If e.KeyChar = Convert.ToChar(13) Then
nexttextbox.setfoucus
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Update: Installing latest version of gcc 9: (gcc 9.3.0) - released March 12, 2020:
Same method can be applied to gcc 10 (gcc 10.1.0) - released May 7, 2020
Download file: gcc-9.3.0.tar.gz or gcc-10.1.0.tar.gz
Compile and install:
//required libraries: (some may already have been installed)
dnf install libmpc-devel mpfr-devel gmp-devel
//if dnf install libmpc-devel is not working try:
dnf --enablerepo=PowerTools install libmpc-devel
//install zlib
dnf install zlib-devel*
./configure --with-system-zlib --disable-multilib --enable-languages=c,c++
make -j 8 <== this may take around an hour or more to finish
(depending on your cpu speed)
make install
Tested under CentOS 7.8.2003 for gcc 9.3 and gcc 10.1
Tested under CentOS 8.1.1911 for gcc 10.1 (may take more time to compile)
Results: gcc/g++ 9.3.0/10.1.0
Installing gcc 7.4 (gcc 7.4.0) - released December 6, 2018:
Download file: https://ftp.gnu.org/gnu/gcc/gcc-7.4.0/gcc-7.4.0.tar.gz
Compile and install:
//required libraries:
yum install libmpc-devel mpfr-devel gmp-devel
./configure --with-system-zlib --disable-multilib --enable-languages=c,c++
make -j 8 <== this may take around 50 minutes or less to finish with 8 threads
(depending on your cpu speed)
make install
Result:
Notes:
1. This Stack Overflow answer will help to see how to verify the downloaded source file.
2. Use the option --prefix
to install gcc to another directory other than the default one. The toplevel installation directory defaults to /usr/local. Read about gcc installation options
Have a look at C++11 Features (Modern C++)
and section "Quick Reference Guide to Visual C++ Version Numbers" ...
Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.
Suppose you have a timedelta series:
import pandas as pd
from datetime import datetime
z = pd.DataFrame({'a':[datetime.strptime('20150101', '%Y%m%d')],'b':[datetime.strptime('20140601', '%Y%m%d')]})
td_series = (z['a'] - z['b'])
One way to convert this timedelta column or series is to cast it to a Timedelta object (pandas 0.15.0+) and then extract the days from the object:
td_series.astype(pd.Timedelta).apply(lambda l: l.days)
Another way is to cast the series as a timedelta64 in days, and then cast it as an int:
td_series.astype('timedelta64[D]').astype(int)
I am using JDK 7 for maven project and I used -Dhttps.protocols=TLSv1.2 as argument in JRE. It has allowed to download all maven repository which were failing earlier.
this:
$('#rblDiv input').click(function(){
alert($('#rblDiv input').index(this));
});
will get you the index of the radio button that was clicked (i think, untested) (note you've had to wrap your RBL in #rblDiv
you could then use that to display the corresponding div like this:
$('.divCollection div:eq(' + $('#rblDiv input').index(this) +')').show();
Is that what you meant?
Edit: Another approach would be to give the rbl a class name, then go:
$('.rblClass').val();
You actually have to use pow(number, power);. Unfortunately, carats don't work as a power sign in C. Many times, if you find yourself not being able to do something from another language, its because there is a diffetent function that does it for you.
If you have access to the C++ 11 libraries, check out the std::chrono
library. You can use it to get the milliseconds since the Unix Epoch like this:
#include <chrono>
// ...
using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);
//----firstly you have to alloc the double and single tap gesture-------//
UITapGestureRecognizer* doubleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleDoubleTap:)];
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleSingleTap:)];
[singleTap requireGestureRecognizerToFail : doubleTap];
[doubleTap setDelaysTouchesBegan : YES];
[singleTap setDelaysTouchesBegan : YES];
//-----------------------number of tap----------------//
[doubleTap setNumberOfTapsRequired : 2];
[singleTap setNumberOfTapsRequired : 1];
//------- add double tap and single tap gesture on the view or button--------//
[self.view addGestureRecognizer : doubleTap];
[self.view addGestureRecognizer : singleTap];
resolve.alias
should work exactly the way you described, so I'm providing this as an answer to help mitigate any confusion that may result from the suggestion in the original question that it does not work.
a resolve configuration like the one below will give you the desired results:
// used to resolve absolute path to project's root directory (where web pack.config.js should be located)
var path = require( 'path' );
...
{
...
resolve: {
// add alias for application code directory
alias:{
mydir: path.resolve( __dirname, 'path', 'to', 'mydir' )
},
extensions: [ '', '.js' ]
}
}
require( 'mydir/myfile.js' )
will work as expected. If it does not, there must be some other issue.
If you have multiple modules that you want to add to the search path, resolve.root
makes sense, but if you just want to be able to reference components within your application code without relative paths, alias
seems to be the most straight-forward and explicit.
An important advantage of alias
is that it gives you the opportunity to namespace your require
s which can add clarity to your code; just like it is easy to see from other require
s what module is being referenced, alias
allows you to write descriptive require
s that make it obvious you're requiring internal modules, e.g. require( 'my-project/component' )
. resolve.root
just plops you into the desired directory without giving you the opportunity to namespace it further.
Another category method you could use:
- (NSArray *) filteredArrayUsingBlock:(BOOL (^)(id obj))block {
NSIndexSet *const filteredIndexes = [self indexesOfObjectsPassingTest:^BOOL (id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
return block(obj);
}];
return [self objectsAtIndexes:filteredIndexes];
}
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
Additional info to generate absolute URL using a command (to send an email for instance)
In a command, {{ absolute_url(path('index')) }}
is not working out of the box.
You will need to add the additional configuration shown in antongorodezkiy's answer.
But in case you don't want to change the configuration because you are not sure how it could impact the whole app, you can configure the router in the command.
Here is the doc :
https://symfony.com/doc/3.4/console/request_context.html
Here is the code :
use Symfony\Component\Routing\RouterInterface;
// ...
class DemoCommand extends Command
{
private $router;
public function __construct(RouterInterface $router)
{
parent::__construct();
$this->router = $router;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$context = $this->router->getContext();
$context->setHost('example.com');
$context->setScheme('https');
$context->setBaseUrl('my/path');
$url = $this->router->generate('route-name', ['param-name' => 'param-value']);
// ...
}
}
To generate the URL in the Twig template
<a href="{{ absolute_url(path(...)) }}"></a>
You can fetch the HOST and SCHEME from your env file
$context = $this->router->getContext();
$context->setHost($_ENV['NL_HOST']);
$context->setScheme($_ENV['NL_SCHEME']);
Just define the variable in .env and .env.local files
NL_HOST=mydomain.com
NL_SCHEME=https
Strange, but I haven't seen the solution like this:
kill -9 `pidof firefox`
it can also kill multiple processes (multiple pids) like:
kill -9 `pgrep firefox`
I prefer pidof
since it has single line output:
> pgrep firefox
6316
6565
> pidof firefox
6565 6316
For adding a new column to an existing CSV file(with headers), if the column to be added has small enough number of values, here is a convenient function (somewhat similar to @joaquin's solution). The function takes the
def add_col_to_csv(csvfile,fileout,new_list):
with open(csvfile, 'r') as read_f, \
open(fileout, 'w', newline='') as write_f:
csv_reader = csv.reader(read_f)
csv_writer = csv.writer(write_f)
i = 0
for row in csv_reader:
row.append(new_list[i])
csv_writer.writerow(row)
i += 1
Example:
new_list1 = ['test_hdr',4,4,5,5,9,9,9]
add_col_to_csv('exists.csv','new-output.csv',new_list1)
I was playing around with cmder (http://gooseberrycreative.com/cmder/) and I wanted to count the lines of html,css,java and javascript. While some of the answers above worked, or
pattern in grep didn't - I found here (https://unix.stackexchange.com/questions/37313/how-do-i-grep-for-multiple-patterns) that I had to escape it
So this is what I use now:
git ls-files | grep "\(.html\|.css\|.js\|.java\)$" | xargs wc -l
A bit late but this should work.
my_dict = {}
my_dict[key] = my_dict[key] + 1 if key in my_dict else 1
If you're worried about performance, check out the Boost::lexical_cast library.
You can use Object.values
in TypeScript by doing this (<any>Object).values(data)
if for some reason you can't update to ES7 in tsconfig.
I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:
Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the username and password fields. In his example, they are inUserName and inUserPass.
Once you've got that, you can use a requests.Session()
instance to make a post request to the login url with your login details as a payload. Making requests from a session instance is essentially the same as using requests normally, it simply adds persistence, allowing you to store and use cookies etc.
Assuming your login attempt was successful, you can simply use the session instance to make further requests to the site. The cookie that identifies you will be used to authorise the requests.
Example
import requests
# Fill in your details here to be posted to the login form.
payload = {
'inUserName': 'username',
'inUserPass': 'password'
}
# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
p = s.post('LOGIN_URL', data=payload)
# print the html returned or something more intelligent to see if it's a successful login page.
print p.text
# An authorised request.
r = s.get('A protected web page url')
print r.text
# etc...
Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.
C:\Windows\SysWOW64>regsvr32 "c:\dll.name"
with jQuery :
html :
<form method="POST" name="myform" action="index.php?action=contact_agent&agent_id=" onsubmit="SetData()">
<select name="agent" id="agent">
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
</form>
jQuery :
$('form').submit(function(){
$(this).attr('action',$(this).attr('action')+$('#agent').val());
$(this).submit();
});
javascript :
function SetData(){
var select = document.getElementById('agent');
var agent_id = select.options[select.selectedIndex].value;
document.myform.action = "index.php?action=contact_agent&agent_id="+agent_id ; # or .getAttribute('action')
myform.submit();
}
The following lines are used to control the listen-port of a server, both are necessary:
<listen-port>7002</listen-port>
<listen-port-enabled>true</listen-port-enabled>
Just use CASCADE
TRUNCATE "products" RESTART IDENTITY CASCADE;
But be ready for cascade deletes )
You can add as many more properties as you like simply by using the dot notation:
var data = {
var1:'somevalue'
}
data.newAttribute = 'newvalue'
or:
data[newattribute] = somevalue
for dynamic keys.
Configure the maven-compiler-plugin to use the same character encoding that your source files are encoded in (e.g):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
Many maven plugins will by default use the "project.build.sourceEncoding" property so setting this in your pom will cover most plugins.
<project>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
...
However, I prefer setting the encoding in each plugin's configuration that supports it as I like to be explicit.
When your source code is compiled by the maven-compiler-plugin your source code files are read in by the compiler plugin using whatever encoding the compiler plugin is configured with. If your source files have a different encoding than the compiler plugin is using then it is possible that some characters may not exist in both encodings.
Many people prefer to set the encoding on their source files to UTF-8 so as to avoid this problem. To do this in Eclipse you can right click on a project and select Properties->Resource->Text File Encoding and change it to UTF-8. This will encode all your source files in UTF-8. (You should also explicitly configure the maven-compiler-plugin as mentioned above to use UTF-8 encoding.) With your source files and the compiler plugin both using the same encoding you shouldn't have any more unmappable characters during compilation.
Note, You can also set the file encoding globally in eclipse through Window->Preferences->General->Workspace->Text File Encoding. You can also set the encoding per file type through Window->Preferences->General->Content Types.
Mozilla 'announces' object extending from ECMAScript 6.0:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends
NOTE: This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.
class Square extends Polygon {
constructor(length) {
// Here, it calls the parent class' constructor with lengths
// provided for the Polygon's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value; }
}
This technology is available in Gecko (Google Chrome / Firefox) - 03/2015 nightly builds.
Stream s;
int len = (int)s.Length;
byte[] b = new byte[len];
int pos = 0;
while((r = s.Read(b, pos, len - pos)) > 0) {
pos += r;
}
A slightly more complicated solution is necesary is s.Length
exceeds Int32.MaxValue
. But if you need to read a stream that large into memory, you might want to think about a different approach to your problem.
Edit: If your stream does not support the Length
property, modify using Earwicker's workaround.
public static class StreamExtensions {
// Credit to Earwicker
public static void CopyStream(this Stream input, Stream output) {
byte[] b = new byte[32768];
int r;
while ((r = input.Read(b, 0, b.Length)) > 0) {
output.Write(b, 0, r);
}
}
}
[...]
Stream s;
MemoryStream ms = new MemoryStream();
s.CopyStream(ms);
byte[] b = ms.GetBuffer();
It's easy with git add -i
. Type a
(for "add untracked"), then *
(for "all"), then q
(to quit) and you're done.
To do it with a single command: echo -e "a\n*\nq\n"|git add -i
List only accepts one type parameter. The closest you'll get with List is:
var list = new List<Tuple<string, int>>();
list.Add(Tuple.Create("hello", 1));
Try adding System.Web
as a reference to your project.
class myClass { protected $foo;
public function __construct(&$var)
{
$this->foo = &$var;
}
public function foo()
{
return ++$this->foo;
}
}
If you are pressed by performance issuses, have a look at GMPY
div#a {
background-image: url('../images/spacer.png');
background-image: none !important;
}
I use a transparent spacer image in addition to the rule to remove the background image because IE6 seems to ignore the background-image: none
even though it is marked !important
.
To override the default entrypoint, use entrypoint
option. To pass the arguments use command
.
Here is the example of replacing bash
with sh
in ubuntu
image:
version: '3'
services:
sh:
entrypoint: /bin/sh
command: -c "ps $$(echo $$$$)"
image: ubuntu
tty: true
bash:
entrypoint: /bin/bash
command: -c "ps $$(echo $$$$)"
image: ubuntu
tty: true
Here is the output:
$ docker-compose up
Starting test_sh_1 ... done
Starting 020211508a29_test_bash_1 ... done
Attaching to test_sh_1, 020211508a29_test_bash_1
sh_1 | PID TTY STAT TIME COMMAND
sh_1 | 1 pts/0 Ss+ 0:00 /bin/sh -c ps $(echo $$)
020211508a29_test_bash_1 | PID TTY STAT TIME COMMAND
020211508a29_test_bash_1 | 1 pts/0 Rs+ 0:00 ps 1
A slight change to Thangamani Palanisamy answer, which allows the Binary reader to be disposed and corrects the input length issue in his comments.
string result = string.Empty;
using (BinaryReader b = new BinaryReader(file.InputStream))
{
byte[] binData = b.ReadBytes(file.ContentLength);
result = System.Text.Encoding.UTF8.GetString(binData);
}
The nuget.exe utility doesn't have this feature, but seeing that the NuGet cache is simply a folder on your computer, you can delete the files manually. Just add this to your batch file:
del %LOCALAPPDATA%\NuGet\Cache\*.nupkg /q
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
If your using the latest version of Itunes and there is no APP section Click on summary while the device is connected to you PC . Then Drag and drop the file onto the "on my device" section.
And if you want the full list of names you can do something like
typeof (PharmacyConfigurationKeys).GetFields()
.Where(x => x.GetCustomAttributes(false).Any(y => typeof(DescriptionAttribute) == y.GetType()))
.Select(x => ((DescriptionAttribute)x.GetCustomAttributes(false)[0]).Description);
First you have to change values in php.ini file as per your requirements.
post_max_size = 1024M
upload_max_filesize = 1024M
max_execution_time = 3600
max_input_time = 3600
memory_limit = 1024M
Note - Change these values carefully. These values will impact for all of your projects of that server.
Now, If above solutions are not working, kindly check your phpmyadmin.conf file. If you are using WAMP so you can find the file in "C:\wamp64\alias".
You have to change below values.
Values already in file are -
php_admin_value upload_max_filesize 128M
php_admin_value post_max_size 128M
php_admin_value max_execution_time 360
php_admin_value max_input_time 360
Change above code to -
# php_admin_value upload_max_filesize 128M
# php_admin_value post_max_size 128M
# php_admin_value max_execution_time 360
# php_admin_value max_input_time 360
Now just restart your server, to work with changed values. :)
Just had the same error message, but when I was running a package.json with:
"scripts": {
"build": "tsc -p ./src",
}
tsc
is the command to run the TypeScript compiler.
I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install
didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev
) to solve the problem.
A chart could make the previous answers easier to understand:
In English,
On the left, note that there is an upper bound and a lower bound that are both of the same order of magnitude (i.e. g(n) ). Ignore the constants, and if the upper bound and lower bound have the same order of magnitude, one can validly say f(n) = T(g(n)) or f(n) is in big theta of g(n).
Starting with the right, the simpler example, it is saying the upper bound g(n) is simply the order of magnitude and ignores the constant c (just as all big O notation does).
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
tar -zcvf compressFileName.tar.gz folderToCompress
everything in folderToCompress will go to compressFileName
Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName
This is possible if you move the fixed <div>
using margins and not positions:
#wrap{ position:absolute;left:100px;top:100px; }
#fixed{
position:fixed;
width:10px;
height:10px;
background-color:#333;
margin-left:200px;
margin-top:200px;
}
And this HTML:
<div id="wrap">
<div id="fixed"></div>
</div>
Play around with this jsfiddle.
You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package
I had this error because I was providing a string of arguments to subprocess.call
instead of an array of arguments. To prevent this, use shlex.split
:
import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)
Thanks digz6666, your solution works for me with a slight changes because I'm using json:
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
The answer given by axtavt (whch you've recommended) wont work for me. Even if I've added the correct media type:
if (conv instanceof StringHttpMessageConverter) { ((StringHttpMessageConverter) conv).setSupportedMediaTypes( Arrays.asList( new MediaType("text", "html", Charset.forName("UTF-8")), new MediaType("application", "json", Charset.forName("UTF-8")) )); }
You usually need to unsubscribe when the components get destroyed, but Angular is going to handle it more and more as we go, for example in new minor version of Angular4, they have this section for routing unsubscribe:
Do you need to unsubscribe?
As described in the ActivatedRoute: the one-stop-shop for route information section of the Routing & Navigation page, the Router manages the observables it provides and localizes the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so you don't need to unsubscribe from the route paramMap Observable.
Also the example below is a good example from Angular to create a component and destroy it after, look at how component implements OnDestroy, if you need onInit, you also can implements it in your component, like implements OnInit, OnDestroy
import { Component, Input, OnDestroy } from '@angular/core';
import { MissionService } from './mission.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'my-astronaut',
template: `
<p>
{{astronaut}}: <strong>{{mission}}</strong>
<button
(click)="confirm()"
[disabled]="!announced || confirmed">
Confirm
</button>
</p>
`
})
export class AstronautComponent implements OnDestroy {
@Input() astronaut: string;
mission = '<no mission announced>';
confirmed = false;
announced = false;
subscription: Subscription;
constructor(private missionService: MissionService) {
this.subscription = missionService.missionAnnounced$.subscribe(
mission => {
this.mission = mission;
this.announced = true;
this.confirmed = false;
});
}
confirm() {
this.confirmed = true;
this.missionService.confirmMission(this.astronaut);
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
}
If you need a body in your response, you can call
return StatusCode(StatusCodes.Status500InternalServerError, responseObject);
This will return a 500 with the response object...
As a temporary fix, users can right click the utility and select "Run as administrator."
You can also simply use @NonNull
with the lombok library instead, at least for the @NotNull
scenario. More details: https://projectlombok.org/api/lombok/NonNull.html
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
In Ubuntu1604 I faced "No installation candidate error". Following below steps helped me install.
-sudo apt-get update -sudo apt-get upgrade -apt-get install software-properties-common -sudo add-apt-repository ppa:webupd8team/java -apt-get update -sudo apt install oracle-java8-installer
As of Amazon Linux version 2017.09 python 3.6 is now available:
sudo yum install python36 python36-virtualenv python36-pip
See the Release Notes for more info and other packages
In order to create an Android Wear emulator you need to follow the instructions below:
If your version of Android SDK Tools is lower than 22.6, you must update
Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.
Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.
Below is the snapshot of what it should look like:
Then you must check the following in order to create a Wearable AVD:
For the Device, select Android Wear Square or Android Wear Round.
For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).
For the CPU/ABI, select Android Wear ARM (armeabi-v7a).
For the Skin, select AndroidWearSquare or AndroidWearRound.
Leave all other options set to their defaults and click OK.
Then you are good to go. For more information you can always refer to the developer site.
To configure your JRE in eclipse:
A few things have changed since the top answers were added. They used to work out for me, but not quite anymore, so I have been hacking around for a bit and came up with the following solution for Ubuntu 16.04. For Ubuntu 14.04, see the comment at the bottom of the answer. Apologies if this doesn't work for shared hosting, but it seems like this is the goto answer for wkhtmltopdf installation instructions in general.
# Install dependencies
apt-get install libfontconfig \
zlib1g \
libfreetype6 \
libxrender1 \
libxext6 \
libx11-6
# TEMPORARY FIX! SEE: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/3001
apt-get install libssl1.0.0=1.0.2g-1ubuntu4.8
apt-get install libssl-dev=1.0.2g-1ubuntu4.8
# Download, extract and move binary in place
curl -L -o wkhtmltopdf.tar.xz https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar -xf wkhtmltopdf.tar.xz
mv wkhtmltox/bin/wkhtmltopdf /usr/local/bin/wkhtmltopdf
chmod +x /usr/local/bin/wkhtmltopdf
Test it out:
wkhtmltopdf http://www.google.com google.pdf
You should now have a file named google.pdf
in the current working directory.
This approach downloads the binary from the website, meaning that you can use the latest version instead of relying on package managers to be updated.
Note that as of today, my solution includes a temporary fix to this bug. I realize that the solution is really not great, but hopefully it can be removed soon. Be sure to check the status of the linked GitHub issue to see if the fix is still necessary when you read this answer!
For Ubuntu 14.04, you will need to downgrade to a different version of libssl. You can find the versions here. Anyways, be sure to consider the implications of downgrading libssl before doing so on any production server.
I hope this helps someone!
len(nams)
should be equal to n
in your code. All indexes 0 <= i < n
"exist".
For me, the carousel wasn't working in the DreamWeaver CC provided the code in the "template" page I am playing with. I needed to add the data-ride="carousel" attribute to the carousel div in order for it to start working. Thanks to Adarsh for his code snippet which highlighted the missing attribute.
Try this way
http://itunes.apple.com/lookup?id="your app ID here" return json.From this, find key "trackViewUrl" and value is the desired url. use this url(just replace https://
with itms-apps://
).This works just fine.
For example if your app ID is xyz then go to this link http://itunes.apple.com/lookup?id=xyz
Then find the url for key "trackViewUrl".This is the url for your app in app store and to use this url in xcode try this
NSString *iTunesLink = @"itms-apps://itunes.apple.com/us/app/Your app name/id Your app ID?mt=8&uo=4";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
Thanks
Firefox supports XHR download progress events.
The provided pieces of code do not cope with Exceptions
May I suggest
getattr(re.search(r"<title>(.*)</title>", s, re.IGNORECASE), 'groups', lambda:[u""])()[0]
This returns an empty string by default if the pattern has not been found, or the first match.
I had a similar issue, trying to run a WCF-based HttpSelfHostServer in Debug under my VisualStudio 2013. I tried every possible direction (turn off firewall, disabling IIS completely to eliminate the possibility localhost port is taken by some other service, etc.).
Eventually, what "did the trick" (solved the problem) was re-running VisualStudio 2013 as Administrator.
Amazing.
I solved by adding a port forwarding in Virtualbox settings under network. Host IP set 127.0.0.1 port : 8080 Guest ip : Give any IP for the website ( say 10.0.2.5) port : 8080 Now from guest machine access http://10.0.2.5:8080 using IE
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
What do you think about this approach?
with open(filename) as data:
datalines = (line.rstrip('\r\n') for line in data)
for line in datalines:
...do something awesome...
Generator expression avoids loading whole file into memory and with
ensures closing the file
On Windows 8.1, IIS 8.5 the solution for me was to register 4.5 from the control panel:
Programs and Features > Turn Windows features on or off > Information Information Services > World Wide Web Services > Application Development Features > Select ASP.NET 4.5
Click OK.
If you are looking to do this in a CI/CD script on Gitlab (gitlab-ci.yml
). You could use
git pull $CI_REPOSITORY_URL
which will translate to something like:
git pull https://gitlab-ci-token:[MASKED]@gitlab.com/gitlab-examples/ci-debug-trace.gi
And I'm pretty sure the token it uses is a ephemeral/per job token - so the security hole with this method is greatly reduced.
select *
FROM XMLTABLE('/person/row'
PASSING
xmltype('
<person>
<row>
<name>Tom</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
<row>
<name>Jim</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
</person>
')
COLUMNS
--describe columns and path to them:
name varchar2(20) PATH './name',
state varchar2(20) PATH './Address/State',
city varchar2(20) PATH './Address/City'
) xmlt
;
No. But it's relatively trivial to achieve using sscanf
in a loop.
Just be warned - When using a Nullable its obviously no longer a 'pure' datetime object, as such you cannot access the DateTime members directly. I'll try and explain.
By using Nullable<> you're basically wrapping DateTime in a container (thank you generics) of which is nullable - obviously its purpose. This container has its own properties which you can call that will provide access to the aforementioned DateTime object; after using the correct property - in this case Nullable.Value - you then have access to the standard DateTime members, properties etc.
So - now the issue comes to mind as to the best way to access the DateTime object. There are a few ways, number 1 is by FAR the best and 2 is "dude why".
Using the Nullable.Value property,
DateTime date = myNullableObject.Value.ToUniversalTime(); //Works
DateTime date = myNullableObject.ToUniversalTime(); //Not a datetime object, fails
Converting the nullable object to datetime using Convert.ToDateTime(),
DateTime date = Convert.ToDateTime(myNullableObject).ToUniversalTime(); //works but why...
Although the answer is well documented at this point, I believe the usage of Nullable was probably worth posting about. Sorry if you disagree.
edit: Removed a third option as it was a bit overly specific and case dependent.
Works for Android KitKat and above (For those who want to transparent the status bar and don't manipulate the NavigationBar, because all of these answers will transparent the NavigationBar too!)
The easiest way to achieve it:
Put these 3 lines of code in the styles.xml (v19)
-> if you don't know how to have this (v19), just write them in your default styles.xml
and then use alt+enter to automatically create it:
<item name="android:windowFullscreen">false</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:fitsSystemWindows">false</item>
And now, go to your MainActivity
Class and put this Method out of onCreate in the class:
public static void setWindowFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
Then put this code in the onCreate
method of the Activity:
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
//make fully Android Transparent Status bar
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
That's it!
You use the ajaxStop to execute code when the ajax are completed:
$(document).ajaxStop(function(){
setTimeout("window.location = 'otherpage.html'",100);
});
mytable:
Value ColOne
--------------------
1 Cleo, Smith
The following should work if there aren't too many columns
ALTER TABLE mytable ADD ColTwo nvarchar(256);
UPDATE mytable SET ColTwo = LEFT(ColOne, Charindex(',', ColOne) - 1);
--'Cleo' = LEFT('Cleo, Smith', Charindex(',', 'Cleo, Smith') - 1)
UPDATE mytable SET ColTwo = REPLACE(ColOne, ColTwo + ',', '');
--' Smith' = REPLACE('Cleo, Smith', 'Cleo' + ',')
UPDATE mytable SET ColOne = REPLACE(ColOne, ',' + ColTwo, ''), ColTwo = LTRIM(ColTwo);
--'Cleo' = REPLACE('Cleo, Smith', ',' + ' Smith', '')
Result:
Value ColOne ColTwo
--------------------
1 Cleo Smith
This is a function that works for me:
function removeFromArray(array, value) {
var idx = array.indexOf(value);
if (idx !== -1) {
array.splice(idx, 1);
}
return array;
}
That your example is invalid is only because you chose a reserved character to start your scalars with. If you replace the *
with some other non-reserved character (I tend to use non-ASCII characters for that as they are seldom used as part of some specification), you end up with perfectly legal YAML:
paths:
root: /path/to/root/
patha: ?root? + a
pathb: ?root? + b
pathc: ?root? + c
This will load into the standard representation for mappings in the language your parser uses and does not magically expand anything.
To do that use a locally default object type as in the following Python program:
# coding: utf-8
from __future__ import print_function
import ruamel.yaml as yaml
class Paths:
def __init__(self):
self.d = {}
def __repr__(self):
return repr(self.d).replace('ordereddict', 'Paths')
@staticmethod
def __yaml_in__(loader, data):
result = Paths()
loader.construct_mapping(data, result.d)
return result
@staticmethod
def __yaml_out__(dumper, self):
return dumper.represent_mapping('!Paths', self.d)
def __getitem__(self, key):
res = self.d[key]
return self.expand(res)
def expand(self, res):
try:
before, rest = res.split(u'?', 1)
kw, rest = rest.split(u'? +', 1)
rest = rest.lstrip() # strip any spaces after "+"
# the lookup will throw the correct keyerror if kw is not found
# recursive call expand() on the tail if there are multiple
# parts to replace
return before + self.d[kw] + self.expand(rest)
except ValueError:
return res
yaml_str = """\
paths: !Paths
root: /path/to/root/
patha: ?root? + a
pathb: ?root? + b
pathc: ?root? + c
"""
loader = yaml.RoundTripLoader
loader.add_constructor('!Paths', Paths.__yaml_in__)
paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']
for k in ['root', 'pathc']:
print(u'{} -> {}'.format(k, paths[k]))
which will print:
root -> /path/to/root/
pathc -> /path/to/root/c
The expanding is done on the fly and handles nested definitions, but you have to be careful about not invoking infinite recursion.
By specifying the dumper, you can dump the original YAML from the data loaded in, because of the on-the-fly expansion:
dumper = yaml.RoundTripDumper
dumper.add_representer(Paths, Paths.__yaml_out__)
print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))
this will change the mapping key ordering. If that is a problem you have
to make self.d
a CommentedMap
(imported from ruamel.yaml.comments.py
)
If you want to stop Git from always asking you for the login credentials of your GitHub repository this can be easily done.
You can update the origin remote using SSH instead of HTTPS"
git remote set-url origin [email protected]:username/your-repo.git
Here’s how you can make Git store the username and password:
git config --global credential.helper store
Next, save the username and password for a session:
git config --global credential.helper cache
To link from a page to another section just use
<a href="index.php#firstdiv">my first div</a>
I used this:
$('.nav-list li.active').removeClass('active');
$(this).parent().addClass('active');
Since the active class is in the <li>
element and what is clicked is the <a>
element, the first line removes .active
from all <li>
and the second one (again, $(this)
represents <a>
which is the clicked element) adds .active
to the direct parent, which is <li>
.
You can go use registry editor.
Using org.apache.commons.io.FileUtils
File file = new File("F:/Lines");
Collection<File> files = FileUtils.listFiles(file, null, true);
for(File file2 : files){
System.out.println(file2.getName());
}
Use false if you do not want files from sub directories.
Just use negative margins, in the second div say:
<div style="margin-top: -25px;">
And make sure to set the z-index property to get the layering you want.
As an alternative, you can also use linq
like this -
string key = string.Join ("",assembly
.GetName()
.GetPublicKeyToken()
.Select (b => b.ToString ("x2")));
SRCS=$(wildcard *.c)
OBJS=$(SRCS:.c=.o)
all: $(OBJS)
You can use vim programmatically with the option -c {command} :
Dos to Unix:
vim file.txt -c "set ff=unix" -c ":wq"
Unix to dos:
vim file.txt -c "set ff=dos" -c ":wq"
"set ff=unix/dos" means change fileformat (ff) of the file to Unix/DOS end of line format
":wq" means write file to disk and quit the editor (allowing to use the command in a loop)
The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready()
then it should work perfectly well:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").show("slow");
});
});
An alternative is to place the <script></script>
at the foot of the page, so it's encountered after the DOM has been loaded and ready.
To make the div
hide again, once the #music
element is clicked, simply use toggle()
:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").toggle();
});
});
And for fading:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").fadeToggle();
});
});
The questions is perfectly valid and clear since Spinner and ComboBox (read it: Spinner where you can provide a custom value as well) are two different things.
I was looking for the same thing myself and I wasn't satisfied with the given answers. So I created my own thing. Perhaps some will find the following hints useful. I am not providing the full source code as I am using some legacy calls in my own project. It should be pretty clear anyway.
Here is the screenshot of the final thing:
The first thing was to create a view that will look the same as the spinner that hasn't been expanded yet. In the screenshot, on the top of the screen (out of focus) you can see the spinner and the custom view right bellow it. For that purpose I used LinearLayout (actually, I inherited from Linear Layout) with style="?android:attr/spinnerStyle"
. LinearLayout contains TextView with style="?android:attr/spinnerItemStyle"
. Complete XML snippet would be:
<com.example.comboboxtest.ComboBox
style="?android:attr/spinnerStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/textView"
style="?android:attr/spinnerItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:singleLine="true"
android:text="January"
android:textAlignment="inherit"
/>
</com.example.comboboxtest.ComboBox>
As, I mentioned earlier ComboBox inherits from LinearLayout. It also implements OnClickListener which creates a dialog with a custom view inflated from the XML file. Here is the inflated view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="Enter custom value ..." >
<requestFocus />
</EditText>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK"
/>
</LinearLayout>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
There are two more listeners that you need to implement: onItemClick for the list and onClick for the button. Both of these set the selected value and dismiss the dialog.
For the list, you want it to look the same as expanded Spinner, you can do that providing the list adapter with the appropriate (Spinner) style like this:
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(
activity,
android.R.layout.simple_spinner_dropdown_item,
states
);
More or less, that should be it.
As for the page, I'm working on a higher order component that uses basically the above methods to do exactly this. It actually takes just a bit of time when you get down to the subtleties like initial layout and content changes. I won't claim to have done it 'correctly', but in some sense I'd consider the correct answer to use component that does this carefully and consistently.
See: react-native-paged-scroll-view. Would love feedback, even if it's that I've done it all wrong!
You can also visit the "Preferences" tab from the H2 Console and shutdown all active sessions by pressing the shutdown button.
The macros defined in <inttypes.h>
are the most correct way to print values of types uint32_t
, uint16_t
, and so forth -- but they're not the only way.
Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf
format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)
An alternative is to cast the values to a predefined type and use the format for that type.
Types int
and unsigned int
are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t
or uint16_t
, respectively. Similarly, long
and unsigned long
are at least 32 bits wide, and long long
and unsigned long long
are at least 64 bits wide.
For example, I might write your program like this (with a few additional tweaks):
#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>
int main(void)
{
uint32_t a=12, a1;
uint16_t b=1, b1;
a1 = htonl(a);
printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
b1 = htons(b);
printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
return 0;
}
One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>
. Such an implementation most likely wouldn't have <stdint.h>
either, but the technique is useful for other integer types.
CheckBoxFor
takes a bool
, you're passing a List<CheckBoxes>
to it. You'd need to do:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
@Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
@Html.HiddenFor(m => m.EmploymentType[i].Text)
@Html.DisplayFor(m => m.EmploymentType[i].Text)
}
Notice I've added a HiddenFor
for the Text
property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.
Edit, as shown in your comments, your EmploymentType
list is null
when the view is served. You'll need to populate that too, by doing this in your action method:
public ActionResult YourActionMethod()
{
CareerForm model = new CareerForm();
model.EmploymentType = new List<CheckBox>
{
new CheckBox { Text = "Fulltime" },
new CheckBox { Text = "Partly" },
new CheckBox { Text = "Contract" }
};
return View(model);
}
I'd probably use all.equal
and which
to get the information you want. It's not recommended to use all.equal
in an if...else
block for some reason, so we wrap it in isTRUE()
. See ?all.equal
for more:
foo <- function(A,B){
if (!isTRUE(all.equal(A,B))){
mismatches <- paste(which(A != B), collapse = ",")
stop("error the A and B does not match at the following columns: ", mismatches )
} else {
message("Yahtzee!")
}
}
And in use:
> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) :
error the A and B does not match at the following columns: 2,4
The conversion is simple:
std::string str; LPCSTR lpcstr = str.c_str();
Use TRY_CAST function in exact same way of CAST function. TRY_CAST takes a string and tries to cast it to a data type specified after the AS keyword. If the conversion fails, TRY_CAST returns a NULL instead of failing.
The REST API for Dropbox, Twitter, Google Web Services and Facebook all uses underscores.
You can use .is(':visible')
to test if something is visible and .is(':hidden')
to test for the opposite:
$('#offers').toggle(!$('#column-left form').is(':visible')); // or:
$('#offers').toggle($('#column-left form').is(':hidden'));
Reference:
I don't know JavaScript and I just started to learn PHP, so what helped for me from all those responses was:
<iframe name="email" style=""></iframe>
<form action="email.php" method="post" target="email">
<input type="email" name="email" >
<input type="submit" name="Submit" value="Submit">
</form>
<?php
if (isset($_POST['Submit'])){
$email = $_POST['email'];
echo $email;
}
?>
<?php
if (isset($_POST['Submit'])){
$to = $_POST['email'];
$subject = "Test email";
$message = "Test message";
$headers = "From: [email protected] \r\n";
$headers .= "Reply-To: [email protected] \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);
}
?>
Hope this helps for all other rookies like me :)
for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
String a = iter.next();
if (...) {
iter.remove();
}
}
Making an additional assumption that the list is of strings.
As already answered, an list.iterator()
is needed. The listIterator can do a bit of navigation too.
Download the source .less
files and make the .border-radius()
mixin blank.
In Workbench 6.3 it is supereasy:
I was having this exact same problem but mine wasn't because I was setting a local variable... I was in a child window, and I needed to set a relative DataContext which I just added to the Window XAML.
<Window x:Class="Log4Net_Viewer.LogItemWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="LogItemWindow" Height="397" Width="572">
You could use a bit of jQuery:
$('input:radio').click(function(){
$('label#' + $(this).attr('id')).toggleClass('checkedClass'); // checkedClass is defined in your CSS
});
You'd need to make sure your checked radio buttons have the correct class on page load as well.
OIDs basically give you a built-in id for every row, contained in a system column (as opposed to a user-space column). That's handy for tables where you don't have a primary key, have duplicate rows, etc. For example, if you have a table with two identical rows, and you want to delete the oldest of the two, you could do that using the oid column.
OIDs are implemented using 4-byte unsigned integers. They are not unique–OID counter will wrap around at 2³²-1. OID are also used to identify data types (see /usr/include/postgresql/server/catalog/pg_type_d.h
).
In my experience, the feature is generally unused in most postgres-backed applications (probably in part because they're non-standard), and their use is essentially deprecated:
In PostgreSQL 8.1 default_with_oids is off by default; in prior versions of PostgreSQL, it was on by default.
The use of OIDs in user tables is considered deprecated, so most installations should leave this variable disabled. Applications that require OIDs for a particular table should specify WITH OIDS when creating the table. This variable can be enabled for compatibility with old applications that do not follow this behavior.
I have just ran into the same problem after updating. The JRE that is downloaded by OSX Lion is missing JavaRuntimeSupport.jar which will work but can wreck havoc on a lot of things. If you've updated, and you had a working JDK/JRE installed prior to that, do the following in Eclipse:
1) Project > Properties > Java Build Path > Select broken JRE/JDK > Edit
2) Select "Alternate JRE"
3) Click "Installed JREs..."
4) In the window that opens, click "Search..."
If all goes well, it will find your older JRE/JDK. Mine was in this location:
/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
You can also do Dictionary:
var list = new List<string> { "a", "b", "a", "c", "a", "b" };
var result = list.GroupBy(x => x)
.ToDictionary(y=>y.Key, y=>y.Count())
.OrderByDescending(z => z.Value);
foreach (var x in result)
{
Console.WriteLine("Value: " + x.Key + " Count: " + x.Value);
}
You could use lodash method _.uniqWith, it is available in the current version of lodash 4.17.2.
Example:
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
More info: https://lodash.com/docs/#uniqWith
If you prefer to use a GUI to create the keys
For a walkthrough on putty gen for the above steps, please see http://ask-leo.com/how_do_i_create_and_use_public_keys_with_ssh.html
pure javascript no jQuery
function sah() {_x000D_
$("#div2").attr("disabled", "disabled").off('click');_x000D_
var x1=$("#div2").hasClass("disabledDiv");_x000D_
_x000D_
(x1==true)?$("#div2").removeClass("disabledDiv"):$("#div2").addClass("disabledDiv");_x000D_
sah1(document.getElementById("div1"));_x000D_
_x000D_
}_x000D_
_x000D_
function sah1(el) {_x000D_
try {_x000D_
el.disabled = el.disabled ? false : true;_x000D_
} catch (E) {}_x000D_
if (el.childNodes && el.childNodes.length > 0) {_x000D_
for (var x = 0; x < el.childNodes.length; x++) {_x000D_
sah1(el.childNodes[x]);_x000D_
}_x000D_
}_x000D_
}
_x000D_
#div2{_x000D_
padding:5px 10px;_x000D_
background-color:#777;_x000D_
width:150px;_x000D_
margin-bottom:20px;_x000D_
}_x000D_
.disabledDiv {_x000D_
pointer-events: none;_x000D_
opacity: 0.4;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
<div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
<input type="text" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="button" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="radio" name="sex" value="Male" />Male_x000D_
<Br />_x000D_
<input type="radio" name="sex" value="Female" />Female_x000D_
<Br />_x000D_
</div>_x000D_
<Br />_x000D_
<Br />_x000D_
<input type="button" value="Click" onclick="sah()" />
_x000D_
I had the same problem for an application deployed to Microsoft Azure.
SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
First I approved all unknown devices (some ip-addresses originating from Ireland) on the following page (signed in as the gmail user): https://security.google.com/settings/u/1/security/secureaccount
I used the following settings for the client:
var client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("[email protected]", "my_password");
It started working only after I set the following property on the smtp-client:
client.TargetName = "STARTTLS/smtp.gmail.com";
For only one line, you need
...
<View android:id="@+id/primerdivisor"
android:layout_height="2dp"
android:layout_width="fill_parent"
android:background="#ffffff" />
...
/
and ..
in the user provided file name can be harmful. So you should get rid of these by something like:
$fname = str_replace('..', '', $fname);
$fname = str_replace('/', '', $fname);
Your html is not updated every 15 seconds. The cause could be browser caching. Add Math.random()
to avoid browser caching, and it's better to wait until the DOM is fully loaded as pointed out by @shadow. But I think the main cause is the caching
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />
<script type="text/javascript">
$(document).ready(function(){
var auto_refresh = setInterval(
function ()
{
$('.View').load('Small.php?' + Math.random()).fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
});
</script>
you can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
Just don't perform e.preventDefault();
, or perform it conditionally.
You certainly can't alter when the original event action occurs.
If you want to "recreate" the original UI event some time later (say, in the callback for an AJAX request) then you'll just have to fake it some other way (like in vzwick's answer)... though I'd question the usability of such an approach.
could also happen when your local time is off (e.g. before certificate validation time), this was the case in my error...
You can add property to your model as follows:
public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }
and then your view will be simpler and will contain no logic at all:
<div class="details @Model.DetailsClass"/>
This will work even with many classes and will not render class if it is null:
<div class="@Model.Class1 @Model.Class2"/>
with 2 not null properties will render:
<div class="class1 class2"/>
if class1 is null
<div class=" class2"/>
Now, 2017, you can do it easier with the new MSTest V2 Framework:
Assert.ThrowsException<Exception>(() => myClass.MyMethodWithError());
//async version
await Assert.ThrowsExceptionAsync<SomeException>(
() => myObject.SomeMethodAsync()
);
<script>
var x = 2; //X is global and value is 2.
function myFunction()
{
x = 7; //x is local variable and value is 7.
}
myFunction();
alert(x); //x is gobal variable and the value is 7
</script>
Ctrl-K, Ctrl-D
Will just prettify the entire document. Saves a lot of messing about, compared to delphi.
Make sure to remove all indents by first selecting everything with Ctrl+A then press Shift+Tab repeatedly until everything is aligned to the left. After you do that Ctrl+K, Ctrl+D will work the way you want them to.
You could also do the same but only to a selection of code by highlighting the block of code you want to realign, aligning it to the left side (Shift+Tab) and then after making sure you've selected the code you want to realign press Ctrl+K, Ctrl+F or just right click the highlighted code and select "Format Selection".
if ($("input[name='html_elements']:checked").size()==0) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
I've had the same issue when some ASP.NET installation was corrupted. In that case they suggest running aspnet_regiis -i -enable
You can pick specific items using destructuring, e.g.:
>>> [first, *middle, last] = range(10)
>>> first
0
>>> middle
[1, 2, 3, 4, 5, 6, 7, 8]
>>> last
9
Note that this is going to consume your generator, so while highly readable, it is less efficient than something like next()
, and ruinous on infinite generators:
>>> [first, *rest] = itertools.count()
This can also happen when you disabled MFA. There will be an old long term entry in the AWS credentials.
Edit the file manually with editor of choice, here using vi (please backup before):
vi ~/.aws/credentials
Then remove the [default-long-term] section. As result in a minimal setup there should be one section [default] left with the actual credentials.
[default-long-term]
aws_access_key_id = ...
aws_secret_access_key = ...
aws_mfa_device = ...
In general you add all prerequisite steps to setUp and all clean-up steps to tearDown.
You can read more with examples here.
When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.
For example you have a test that requires items to exist, or certain state - so you put these actions(creating object instances, initializing db, preparing rules and so on) into the setUp.
Also as you know each test should stop in the place where it was started - this means that we have to restore app state to it's initial state - e.g close files, connections, removing newly created items, calling transactions callback and so on - all these steps are to be included into the tearDown.
So the idea is that test itself should contain only actions that to be performed on the test object to get the result, while setUp and tearDown are the methods to help you to leave your test code clean and flexible.
You can create a setUp and tearDown for a bunch of tests and define them in a parent class - so it would be easy for you to support such tests and update common preparations and clean ups.
If you are looking for an easy example please use the following link with example
Combine Dynamic SQL with OpenQuery. (This goes to a Teradata server)
DECLARE
@dayOfWk TINYINT = DATEPART(DW, GETDATE()),
@qSQL NVARCHAR(MAX) = '';
SET @qSQL = '
SELECT
*
FROM
OPENQUERY(TERASERVER,''
SELECT DISTINCT
CASE
WHEN ' + CAST(@dayOfWk AS NCHAR(1)) + ' = 2
THEN ''''Monday''''
ELSE ''''Not Monday''''
END
'');';
EXEC sp_executesql @qSQL;
Just put your credentials in the Url like this:
https://Username
:Password
@github.com/myRepoDir/myRepo.git
You may store it like this:
git remote add myrepo https://Userna...
...example to use it:
git push myrepo master
Now that is to List the url aliases:
git remote -v
...and that the command to delete one of them:
git remote rm myrepo
If you're using Python 2.x, try installing a urllib2 opener. That should print out your headers, although you may have to combine that with other openers you're using to hit the HTTPS.
import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)
Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.
You can check this by running in Windows PowerShell:
> Get-Service ssh-agent
And then check the output of status is not running.
Status Name DisplayName
------ ---- -----------
Stopped ssh-agent OpenSSH Authentication Agent
Then check that the service has been disabled by running
> Get-Service ssh-agent | Select StartType
StartType
---------
Disabled
I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:
> Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Alternatively, you can set it through the GUI if you prefer.
cell.imageView.image = [UIImage imageNamed:@"image.png"];
UPDATE: Like Steven Fisher said, this should only work for cells with style UITableViewCellStyleDefault which is the default style. For other styles, you'd need to add a UIImageView to the cell's contentView.
you can use success function, once see this jquery.ajax settings
$('#ChangePermission').click(function(){
$.ajax({
url: 'change_permission.php',
type: 'POST',
data: {
'user': document.GetElementById("user").value,
'perm': document.GetElementById("perm").value
}
success:function(result)//we got the response
{
//you can try to write alert(result) to see what is the response,this result variable will contains what you prints in the php page
}
})
})
we can also have error() function
hope this helps you
In Kotlin you can do this...
Service:
class MyService : Service() {
init {
instance = this
}
companion object {
lateinit var instance: MyService
fun terminateService() {
instance.stopSelf()
}
}
}
In your activity (or anywhere in your app for that matter):
btn_terminate_service.setOnClickListener {
MyService.terminateService()
}
Note: If you have any pending intents showing a notification in Android's status bar, you may want to terminate that as well.
You can also open the file in r+
mode and then set the file position to the end of the file.
import os
with open('text.txt', 'r+') as f:
f.seek(0, os.SEEK_END)
f.write("text to add")
Opening the file in r+
mode will let you write to other file positions besides the end, while a
and a+
force writing to the end.
Well, as the error says, you have an expression (((t[1])/length) * t[1]
) on the left side of the assignment, rather than a variable name. You have that expression, and then you tell Python to add string
to it (which is always ""
) and assign it to... where? ((t[1])/length) * t[1]
isn't a variable name, so you can't store the result into it.
Did you mean string += ((t[1])/length) * t[1]
? That would make more sense. Of course, you're still trying to add a number to a string, or multiply by a string... one of those t[1]
s should probably be a t[0]
.
Given a csv file with a datetime column in this format: yyyy-mm-dd hh:mm:ss
Excel shows it in this format: dd/mm/yyyy hh:mm
e.g. 2020-05-22 16:40:55 shows as 22/05/2020 16:40
This is evidently determined by the Short date and Short time format selected in Windows; for example, if I change the Short date format in Windows to yyyy-mm-dd, Excel shows 2020-05-22 16:40.
Annoyingly, I can't find any way to make Excel show the seconds automatically (I have to manually format the column in Excel). But if the csv file includes a time column in hh:mm:ss format (e.g. 16:40:55), that's what shows in Excel, including the seconds.
You don't need to downgrade you can:
Either disable undefined symbol diagnostics in the settings -- "intelephense.diagnostics.undefinedSymbols": false .
Or use an ide helper that adds stubs for laravel facades. See https://github.com/barryvdh/laravel-ide-helper
var myDiv = document.getElementById('containerDiv');
myDiv.innerHTML = variableLongText;
myDiv.scrollTop = 0;
See the scrollTop
attribute.
As per a request by @user5359531 in the comments under @John T's answer, here's a copy of the referenced post to the revised version of the linked discussion in that answer:
Issue of redirecting the stdout to both file and screen
Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon May 28 12:45:51 CEST 2007
Previous message: Issue of redirecting the stdout to both file and screen
Next message: Formal interfaces with Python
Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
En Mon, 28 May 2007 06:17:39 -0300, ???????,???????
<kelvin.you at gmail.com> escribió:
> I wanna print the log to both the screen and file, so I simulatered a
> 'tee'
>
> class Tee(file):
>
> def __init__(self, name, mode):
> file.__init__(self, name, mode)
> self.stdout = sys.stdout
> sys.stdout = self
>
> def __del__(self):
> sys.stdout = self.stdout
> self.close()
>
> def write(self, data):
> file.write(self, data)
> self.stdout.write(data)
>
> Tee('logfile', 'w')
> print >>sys.stdout, 'abcdefg'
>
> I found that it only output to the file, nothing to screen. Why?
> It seems the 'write' function was not called when I *print* something.
You create a Tee instance and it is immediately garbage collected. I'd
restore sys.stdout on Tee.close, not __del__ (you forgot to call the
inherited __del__ method, btw).
Mmm, doesn't work. I think there is an optimization somewhere: if it looks
like a real file object, it uses the original file write method, not yours.
The trick would be to use an object that does NOT inherit from file:
import sys
class TeeNoFile(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def close(self):
if self.stdout is not None:
sys.stdout = self.stdout
self.stdout = None
if self.file is not None:
self.file.close()
self.file = None
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
def __del__(self):
self.close()
tee=TeeNoFile('logfile', 'w')
print 'abcdefg'
print 'another line'
tee.close()
print 'screen only'
del tee # should do nothing
--
Gabriel Genellina
It sounds like you're trying to link with your resulting object file with gcc
instead of g++
:
Note that programs using C++ object files must always be linked with g++, in order to supply the appropriate C++ libraries. Attempting to link a C++ object file with the C compiler gcc will cause "undefined reference" errors for C++ standard library functions:
$ g++ -Wall -c hello.cc
$ gcc hello.o (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
undefined reference to `__gxx_personality_v0'
Source: An Introduction to GCC - for the GNU compilers gcc and g++
in the DBAdaper i.e Data Base helper class declare the table like this
private static final String USERDETAILS=
"create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);";
insert the values like this,
first convert the images as byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] photo = baos.toByteArray();
db.insertUserDetails(value1,value2, value3, photo,value2);
in DEAdaper class
public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility)
{
ContentValues initialValues = new ContentValues();
initialValues.put("username", uname);
initialValues.put("userid",userid);
initialValues.put("password", pass);
initialValues.put("photo",photo);
initialValues.put("visibility",visibility);
return db.insert("userdetails", null, initialValues);
}
retrieve the image as follows
Cursor cur=your query;
while(cur.moveToNext())
{
byte[] photo=cur.getBlob(index of blob cloumn);
}
convert the byte[] into image
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
I think this content may solve your problem
The consequence of this is that you may need a rather insane-looking query, e. g.,
SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID] AS lngRecordID
,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName] AS vcrSourceWorkbookName
,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName] AS vcrImportFileName
,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime] AS dtmLastWriteTime
,[dbo].[tblTimeSheetExportFiles].[lngNRecords] AS lngNRecords
,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk] AS lngSizeOnDisk
,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity] AS lngLastIdentity
,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
,MIN ( [tblTimeRecords].[dtmActivity_Date] ) AS dtmPeriodFirstWorkDate
,MAX ( [tblTimeRecords].[dtmActivity_Date] ) AS dtmPeriodLastWorkDate
,SUM ( [tblTimeRecords].[decMan_Hours_Actual] ) AS decHoursWorked
,SUM ( [tblTimeRecords].[decAdjusted_Hours] ) AS decHoursBilled
FROM [dbo].[tblTimeSheetExportFiles]
LEFT JOIN [dbo].[tblTimeRecords]
ON [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
GROUP BY [dbo].[tblTimeSheetExportFiles].[lngRecordID]
,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]
Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.
You can add a new formula for unique record count
=IF(COUNTIF($A$2:A2,A2)>1,0,1)
Now you can use a pivot table and get a SUM
of unique record count.
This solution works best if you have two or more rows where the same value exist, but you want the pivot table to report an unique count.
Simple using jquery
<script>
$(document).ready(function() {
$('#loginLink').click(function() {
$('#loginTable').toggle('slow');
});
})
</script>
The default font on windows 10 is Consolas
Another approach
Say you create a class clsBitcoinPublicKey
In the class module create an ADDITIONAL subroutine, that acts as you would want the real constructor to behave. Below I have named it ConstructorAdjunct.
Public Sub ConstructorAdjunct(ByVal ...)
...
End Sub
From the calling module, you use an additional statement
Dim loPublicKey AS clsBitcoinPublicKey
Set loPublicKey = New clsBitcoinPublicKey
Call loPublicKey.ConstructorAdjunct(...)
The only penalty is the extra call, but the advantage is that you can keep everything in the class module, and debugging becomes easier.
You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"
Here is how:
<a href="#go_middle">Go Middle</a>
<div id="go_middle">Hello There</div>
For this case to import Bar.py into Foo.py, first I'd turn these folders into Python packages like so:
dirFoo\
__init__.py
Foo.py
dirBar\
__init__.py
Bar.py
Then I would do it like this in Foo.py:
from .dirBar import Bar
If I wanted the namespacing to look like Bar.whatever, or
from . import dirBar
If I wanted the namespacing dirBar.Bar.whatever. This second case is useful if you have more modules under the dirBar package.
the val
function called from the select
will return an array if its a multiple. $('select#my_multiselect').val()
will return an array of the values for the selected options - you dont need to loop through and get them yourself.
The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.
When page has no meta viewport tag:
When page has either of these two meta tags:
<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">
<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">
With <meta name="viewport" content="width=device-width">
:
With <meta name="viewport" content="height=device-height">
:
With <meta name="viewport" content="height=device-height,width=device-width">
:
With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">
With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
Actually, when you use git reset
, you should refer to the commit that you are resetting to; so you would want the db0c078
commit, probably.
An easier version would be git reset --hard HEAD^
, to reset to the previous commit before the current head; that way you don't have to be copying around commit IDs.
Beware when you do any git reset --hard
, as you can lose any uncommitted changes you have. You might want to check git status
to make sure your working copy is clean, or that you do want to blow away any changes that are there.
In addition, instead of HEAD you can use origin/master
as reference, as suggested by @bdonlan in the comments: git reset --hard origin/master
I understood your question I think you are confusing it with languages like dot.net and java where you can open DB connection within your code. No, JavaScript can not directly connect to MySQL as JavaScript is a client side scripting language(Exception Node.js).You need a middle layer like RESTful API to access data.
Change:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
To:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))
This also occurs when you don't set the form action.
For me, it was showing this error when the code was:
<form class="navbar-form form-inline my-2 my-lg-0" role="search" method="post">
When I corrected my code into this:
<form class="navbar-form form-inline my-2 my-lg-0" action="{% url 'someurl' %}" role="search" method="post">
my error disappeared.
Taking @chrissr's answer and running with it, this code can be implemented into a nice category on NSUserDefaults
to save and retrieve custom objects:
@interface NSUserDefaults (NSUserDefaultsExtensions)
- (void)saveCustomObject:(id<NSCoding>)object
key:(NSString *)key;
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key;
@end
@implementation NSUserDefaults (NSUserDefaultsExtensions)
- (void)saveCustomObject:(id<NSCoding>)object
key:(NSString *)key {
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[self setObject:encodedObject forKey:key];
[self synchronize];
}
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key {
NSData *encodedObject = [self objectForKey:key];
id<NSCoding> object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
@end
Usage:
[[NSUserDefaults standardUserDefaults] saveCustomObject:myObject key:@"myKey"];
Install rubygems-update
gem install rubygems-update
update_rubygems
gem update --system
run this commands as root or use sudo.
Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait,
and wait short time in every loop.
This will result in something like
max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
if [ -f /tmp/st_new.tmp ]; then
break # call results.sh outside loop
else
(( retry = retry + 1 ))
sleep 1
fi
done
if [ -f /tmp/st_new.tmp ]; then
source ../../results.sh
rm -f /tmp/st_new.tmp
else
echo Something wrong with st_new.sh
fi
To call a function inside a same controller in any laravel version follow as bellow
$role = $this->sendRequest('parameter');
// sendRequest is a public function
dict1={'a':1, 'b':'banana'}
To list the dictionary in Python 2.x:
for k,v in dict1.iteritems():
print k,v
In Python 3.x use:
for k,v in dict1.items():
print(k,v)
# a 1
# b banana
Finally, as others have indicated, if you want a running index, you can have that too:
for i in enumerate(dict1.items()):
print(i)
# (0, ('a', 1))
# (1, ('b', 'banana'))
But this defeats the purpose of a dictionary (map, associative array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use OrderedDict instead.
Just put below code in AndroidManifest :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
As an extension to John Galt's answer -
For the following DataFrame,
customer item1 item2 item3
0 1 apple milk tomato
1 2 water orange potato
2 3 juice mango chips
If you want to get a list of dictionaries including the index values, you can do something like,
df.to_dict('index')
Which outputs a dictionary of dictionaries where keys of the parent dictionary are index values. In this particular case,
{0: {'customer': 1, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
1: {'customer': 2, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
2: {'customer': 3, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}}
Whatever goes to softmax
is logit, this is what J. Hinton repeats in coursera videos all the time.
My answer is intended for comment though but since i havent got enough reputation, i think it will still be relevant as an answer and help some one.
I find datatable
in library DT
robust to handle rownames
, and columnames
Library DT
datatable(df, rownames = FALSE) # no row names
refer to https://rstudio.github.io/DT/ for usage scenarios
Here are two jQuery patches to help out (maybe already included in jQuery by the time you are reading this):
This is what I use and it works in Linux environments. I don't think this would work on a Windows machine...
//define canonicalized absolute pathname for the script
if(substr($_SERVER['SCRIPT_NAME'],0,1) == DIRECTORY_SEPARATOR) {
//does the script name start with the directory separator?
//if so, the path is defined from root; may have symbolic references so still use realpath()
$script = realpath($_SERVER['SCRIPT_NAME']);
} else {
//otherwise prefix script name with the current working directory
//and use realpath() to resolve symbolic references
$script = realpath(getcwd() . DIRECTORY_SEPARATOR . $_SERVER['SCRIPT_NAME']);
}
You can use the following to get the root directory of a website project:
String FilePath;
FilePath = Server.MapPath("/MyWebSite");
Or you can get the base directory like so:
AppDomain.CurrentDomain.BaseDirectory
This will serve the purpose. There is no need for any divs or paragraph. If you want the spaces between them to be specified, use margin-left or margin-right in the css classes.
<div style="width:500px;">
<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
</div>
I know this is an old post, but here's how I solved it (along with converting null values to empty string) in C# using an extension method.
Create a static class with something like the following:
/// <summary>
/// Wraps value in quotes if necessary and converts nulls to empty string
/// </summary>
/// <param name="value"></param>
/// <returns>String ready for use in CSV output</returns>
public static string Q(this string value)
{
if (value == null)
{
return string.Empty;
}
if (value.Contains(",") || (value.Contains("\"") || value.Contains("'") || value.Contains("\\"))
{
return "\"" + value + "\"";
}
return value;
}
Then for each string you're writing to CSV, instead of:
stringBuilder.Append( WhateverVariable );
You just do:
stringBuilder.Append( WhateverVariable.Q() );