A slight change to Alex's answer, but using __next__()
:
print(next(os.walk('d:/'))[2])
or
print(os.walk('d:/').__next__()[2])
with the [2]
being the file
in root, dirs, file
mentioned in other answers
If you don't mind installing an additional light library, you can do this:
pip install plazy
Usage:
import plazy
txt_filter = lambda x : True if x.endswith('.txt') else False
files = plazy.list_files(root='data', filter_func=txt_filter, is_include_root=True)
The result should look something like this:
['data/a.txt', 'data/b.txt', 'data/sub_dir/c.txt']
It works on both Python 2.7 and Python 3.
Github: https://github.com/kyzas/plazy#list-files
Disclaimer: I'm an author of plazy
.
This does it for folder names:
def printFolderName(init_indent, rootFolder):
fname = rootFolder.split(os.sep)[-1]
root_levels = rootFolder.count(os.sep)
# os.walk treats dirs breadth-first, but files depth-first (go figure)
for root, dirs, files in os.walk(rootFolder):
# print the directories below the root
levels = root.count(os.sep) - root_levels
indent = ' '*(levels*2)
print init_indent + indent + root.split(os.sep)[-1]
For people who want to use another diff tool not listed in git, say with nvim
. here is what I ended up using:
git config --global alias.d difftool -x <tool name>
In my case, I set <tool name>
to nvim -d
and invoke the diff command with
git d <file>
When i Tried your Code i got en Error when i wanted to fill the Array.
you can try to fill the Array like This.
Sub Testing_Data()
Dim k As Long, S2 As Worksheet, VArray
Application.ScreenUpdating = False
Set S2 = ThisWorkbook.Sheets("Sheet1")
With S2
VArray = .Range("A1:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
End With
For k = 2 To UBound(VArray, 1)
S2.Cells(k, "B") = VArray(k, 1) / 100
S2.Cells(k, "C") = VArray(k, 1) * S2.Cells(k, "B")
Next
End Sub
This is similar to C#'s way of doing it in C++
In C# file.cs you can have private var inside a public function. When in another file you can use it by calling the namespace with the function as in:
MyNamespace.Function(blah);
Here's how to imp the same in C++:
SharedModule.h
class TheDataToBeHidden
{
public:
static int _var1;
static int _var2;
};
namespace SharedData
{
void SetError(const char *Message, const char *Title);
void DisplayError(void);
}
SharedModule.cpp
//Init the data (Link error if not done)
int TheDataToBeHidden::_var1 = 0;
int TheDataToBeHidden::_var2 = 0;
//Implement the namespace
namespace SharedData
{
void SetError(const char *Message, const char *Title)
{
//blah using TheDataToBeHidden::_var1, etc
}
void DisplayError(void)
{
//blah
}
}
OtherFile.h
#include "SharedModule.h"
OtherFile.cpp
//Call the functions using the hidden variables
SharedData::SetError("Hello", "World");
SharedData::DisplayError();
it is better to use json after post your resuest like below
var clien = new RestClient("https://smple.com/");
var request = new RestRequest("index", Method.POST);
request.AddHeader("Sign", signinstance);
request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
var response = client.Execute<YourReturnclassSample>(request);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
return Ok(response.Content);
}
Using the @WebFilter annotation, it can be done as follows:
@WebFilter(urlPatterns = {"/*" })
public class AuthenticationFilter implements Filter{
private static Logger logger = Logger.getLogger(AuthenticationFilter.class);
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info("checking client id in filter");
HttpServletRequest request = (HttpServletRequest) arg0;
String clientId = request.getHeader("clientId");
if (StringUtils.isNotEmpty(clientId)) {
chain.doFilter(request, response);
} else {
logger.error("client id missing.");
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
This solution is basically pushing
List<Object>
data to Excel, It uses DataTable to achieve this, I implemented an extension method, so basically there are two things needed. 1. An Extension Method.
public static class ReportHelper
{
public static string ToExcel<T>(this IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
{
//table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
if (prop.Attributes[typeof(FGMS.Entity.Extensions.ReportHeaderAttribute)] != null)
{
table.Columns.Add(GetColumnHeader(prop), Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
}
//So it seems like when there is only one row of data the headers do not appear
//so adding a dummy blank row which fixed the issues
//Add a blank Row - Issue # 1471
DataRow blankRow = table.NewRow();
table.Rows.Add(blankRow);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
//row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
if (prop.Attributes[typeof(FGMS.Entity.Extensions.ReportHeaderAttribute)] != null)
{
row[GetColumnHeader(prop)] = prop.GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(row);
}
table.TableName = "Results";
var filePath = System.IO.Path.GetTempPath() + "\\" + System.Guid.NewGuid().ToString() + ".xls";
table.WriteXml(filePath);
return filePath;
}
private static string GetColumnHeader(PropertyDescriptor prop)
{
return ((FGMS.Entity.Extensions.ReportHeaderAttribute)(prop.Attributes[typeof(FGMS.Entity.Extensions.ReportHeaderAttribute)])).ReportHeaderText;
}
}
- Decorate your DTO classes with the Attribute
[ReportHeaderAttribute("Column Name")]
public class UserDTO
{
public int Id { get; set; }
public int SourceId { get; set; }
public string SourceName { get; set; }
[ReportHeaderAttribute("User Type")]
public string UsereType { get; set; }
[ReportHeaderAttribute("Address")]
public string Address{ get; set; }
[ReportHeaderAttribute("Age")]
public int Age{ get; set; }
public bool IsActive { get; set; }
[ReportHeaderAttribute("Active")]
public string IsActiveString
{
get
{
return IsActive ? "Yes" : "No";
}
}}
Everything that needs to be a column in the Excel has to be decorated with [ReportHeaderAttribute("Column Name")]
Then Simply
Var userList = Service.GetUsers() //Returns List of UserDTO;
var excelFilePath = userList.ToExcel();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(excelFilePath, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/vnd.ms-excel");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "UserList.xls" };
return result;
In XML you can add this line to the EditText
View
where 140 is the maximum number of characters:
android:maxLength="140"
Contruct your url via click event handler:
string strUrl = "/some/url/path" + myvar;
Then:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + strUrl + "','_blank')", true);
You could listen to the 'keydown'
event and then check for an enter key.
Your handler would be like:
function (e) {
if (13 == e.keyCode) {
... do whatever ...
}
}
I developed a generic statement to apply the filter:
string rowFilter = string.Format("[{0}] = '{1}'", columnName, filterValue);
(myDataGridView.DataSource as DataTable).DefaultView.RowFilter = rowFilter;
The square brackets allow for spaces in the column name.
Additionally, if you want to include multiple values in your filter, you can add the following line for each additional value:
rowFilter += string.Format(" OR [{0}] = '{1}'", columnName, additionalFilterValue);
Use ` backticks for MYSQL reserved words...
table name "table" is reserved word for MYSQL...
so your query should be as follows...
$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";
Get cursor on top, where white header with file name, then press Alt. To set top menu by default always visible. You needed in top menu selected: FILE -> Config... -> autoHideMenuBar: true (change it to autoHideMenuBar: false) Save it.
I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))
This worked for me on macOS 10.13.6 with 8.0.12 MySQL
/usr/local/mysql/support-files/mysql.server start
/usr/local/mysql/support-files/mysql.server restart
/usr/local/mysql/support-files/mysql.server stop
Note the guidelines for performing work on a UI thread, collected on my blog:
There are two techniques you should use:
1) Use ConfigureAwait(false)
when you can.
E.g., await MyAsync().ConfigureAwait(false);
instead of await MyAsync();
.
ConfigureAwait(false)
tells the await
that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async
method (after the ConfigureAwait
), you cannot do anything that assumes you're in the current context (e.g., update UI elements).
For more information, see my MSDN article Best Practices in Asynchronous Programming.
2) Use Task.Run
to call CPU-bound methods.
You should use Task.Run
, but not within any code you want to be reusable (i.e., library code). So you use Task.Run
to call the method, not as part of the implementation of the method.
So purely CPU-bound work would look like this:
// Documentation: This method is CPU-bound.
void DoWork();
Which you would call using Task.Run
:
await Task.Run(() => DoWork());
Methods that are a mixture of CPU-bound and I/O-bound should have an Async
signature with documentation pointing out their CPU-bound nature:
// Documentation: This method is CPU-bound.
Task DoWorkAsync();
Which you would also call using Task.Run
(since it is partially CPU-bound):
await Task.Run(() => DoWorkAsync());
A simple approach would be to use the /MIR option, to mirror the two directories. Basically it will copy only the new files to destination. In next comand replace source and destination with the paths to your folders, the script will search for any file with any extensions.
robocopy <source directory> <destination directory> *.* /MIR
I also thought this would work but it's misleading:
myStruct _m1 = {0};
When I tried this:
myStruct _m1 = {0xff};
Only the 1st byte was set to 0xff
, the remaining ones were set to 0
. So I wouldn't get into the habit of using this.
UPDATE: 9/24/16 Angular 2.0 Stable
This question gets a lot of traffic still, so, I wanted to update it. With the insanity of changes from Alpha, Beta, and 7 RC candidates, I stopped updating my SO answers until they went stable.
This is the perfect case for using Subjects and ReplaySubjects
I personally prefer to use ReplaySubject(1)
as it allows the last stored value to be passed when new subscribers attach even when late:
let project = new ReplaySubject(1);
//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result));
http.get('path/to/whatever/projects/1234').subscribe(result => {
//push onto subject
project.next(result));
//add delayed subscription AFTER loaded
setTimeout(()=> project.subscribe(result => console.log('Delayed Stream:', result)), 3000);
});
//Output
//Subscription Streaming: 1234
//*After load and delay*
//Delayed Stream: 1234
So even if I attach late or need to load later I can always get the latest call and not worry about missing the callback.
This also lets you use the same stream to push down onto:
project.next(5678);
//output
//Subscription Streaming: 5678
But what if you are 100% sure, that you only need to do the call once? Leaving open subjects and observables isn't good but there's always that "What If?"
That's where AsyncSubject comes in.
let project = new AsyncSubject();
//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result),
err => console.log(err),
() => console.log('Completed'));
http.get('path/to/whatever/projects/1234').subscribe(result => {
//push onto subject and complete
project.next(result));
project.complete();
//add a subscription even though completed
setTimeout(() => project.subscribe(project => console.log('Delayed Sub:', project)), 2000);
});
//Output
//Subscription Streaming: 1234
//Completed
//*After delay and completed*
//Delayed Sub: 1234
Awesome! Even though we closed the subject it still replied with the last thing it loaded.
Another thing is how we subscribed to that http call and handled the response. Map is great to process the response.
public call = http.get(whatever).map(res => res.json())
But what if we needed to nest those calls? Yes you could use subjects with a special function:
getThing() {
resultSubject = new ReplaySubject(1);
http.get('path').subscribe(result1 => {
http.get('other/path/' + result1).get.subscribe(response2 => {
http.get('another/' + response2).subscribe(res3 => resultSubject.next(res3))
})
})
return resultSubject;
}
var myThing = getThing();
But that's a lot and means you need a function to do it. Enter FlatMap:
var myThing = http.get('path').flatMap(result1 =>
http.get('other/' + result1).flatMap(response2 =>
http.get('another/' + response2)));
Sweet, the var
is an observable that gets the data from the final http call.
OK thats great but I want an angular2 service!
I got you:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ReplaySubject } from 'rxjs';
@Injectable()
export class ProjectService {
public activeProject:ReplaySubject<any> = new ReplaySubject(1);
constructor(private http: Http) {}
//load the project
public load(projectId) {
console.log('Loading Project:' + projectId, Date.now());
this.http.get('/projects/' + projectId).subscribe(res => this.activeProject.next(res));
return this.activeProject;
}
}
//component
@Component({
selector: 'nav',
template: `<div>{{project?.name}}<a (click)="load('1234')">Load 1234</a></div>`
})
export class navComponent implements OnInit {
public project:any;
constructor(private projectService:ProjectService) {}
ngOnInit() {
this.projectService.activeProject.subscribe(active => this.project = active);
}
public load(projectId:string) {
this.projectService.load(projectId);
}
}
I'm a big fan of observers and observables so I hope this update helps!
Original Answer
I think this is a use case of using a Observable Subject or in Angular2
the EventEmitter
.
In your service you create a EventEmitter
that allows you to push values onto it. In Alpha 45 you have to convert it with toRx()
, but I know they were working to get rid of that, so in Alpha 46 you may be able to simply return the EvenEmitter
.
class EventService {
_emitter: EventEmitter = new EventEmitter();
rxEmitter: any;
constructor() {
this.rxEmitter = this._emitter.toRx();
}
doSomething(data){
this.rxEmitter.next(data);
}
}
This way has the single EventEmitter
that your different service functions can now push onto.
If you wanted to return an observable directly from a call you could do something like this:
myHttpCall(path) {
return Observable.create(observer => {
http.get(path).map(res => res.json()).subscribe((result) => {
//do something with result.
var newResultArray = mySpecialArrayFunction(result);
observer.next(newResultArray);
//call complete if you want to close this stream (like a promise)
observer.complete();
});
});
}
That would allow you do this in the component:
peopleService.myHttpCall('path').subscribe(people => this.people = people);
And mess with the results from the call in your service.
I like creating the EventEmitter
stream on its own in case I need to get access to it from other components, but I could see both ways working...
Here's a plunker that shows a basic service with an event emitter: Plunkr
I was recently tasked with this as well.
We wanted to allow our programmers to modify only their own commit messages, and restrict how far back they are allowed to do so. We decided they would be allowed to modify any log messages committed that day, to fix typo's etc.
After looking at a couple other examples online I hacked this together, we are in a windows environment, so this is our contents of pre-revprop-change.bat
:
@ECHO OFF
set repos=%1
set rev=%2
set user=%3
set propname=%4
set action=%5
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Only allow changes to svn:log. The author, date and other revision
:: properties cannot be changed
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
if /I not '%propname%'=='svn:log' goto ERROR_PROPNAME
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Only allow modifications to svn:log (no addition/overwrite or deletion)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
if /I not '%action%'=='M' goto ERROR_ACTION
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Only allow user to modify their own log messages
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set AUTHOR=
for /f "delims=" %%a in ('svnlook author -r %REV% %REPOS%') do @set AUTHOR=%%a
if /I not '%AUTHOR%'=='%user%' goto ERROR_WRONGUSER
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Only allow user to modify log messages from today, old messages locked down
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set DATESTAMP=
for /f "delims=" %%a in ('svnlook date -r %REV% %REPOS%') do @set DATESTAMP=%%a
for /F "tokens=1-2 delims= " %%a in ("%DATESTAMP%") do (
set DATESTAMPDATE=%%a
set DATESTAMPTIME=%%b )
:: Expects DATESTAMPDATE in the format: 2012-02-24
for /F "tokens=1-3 delims=-" %%a in ("%DATESTAMPDATE%") do (
set DATESTAMPYEAR=%%a
set DATESTAMPMONTH=%%b
set DATESTAMPDAY=%%c )
:: Expects date in the format: Thu 08/01/2013
for /F "tokens=1-4 delims=/ " %%a in ("%date%") do (
set YEAR=%%d
set MONTH=%%b
set DAY=%%c )
if /I not '%DATESTAMPYEAR%'=='%YEAR%' goto ERROR_MSGTOOOLD
if /I not '%DATESTAMPMONTH%'=='%MONTH%' goto ERROR_MSGTOOOLD
if /I not '%DATESTAMPDAY%'=='%DAY%' goto ERROR_MSGTOOOLD
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Make sure that the new svn:log message contains some text.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if '%bIsEmpty%'=='true' goto ERROR_EMPTY
goto :eof
:ERROR_EMPTY
echo Empty svn:log properties are not allowed. >&2
goto ERROR_EXIT
:ERROR_PROPNAME
echo Only changes to svn:log revision properties are allowed. >&2
goto ERROR_EXIT
:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT
:ERROR_WRONGUSER
echo You are not allowed to modify other user's log messages. >&2
goto ERROR_EXIT
:ERROR_MSGTOOOLD
echo You are not allowed to modify log messages older than today. >&2
goto ERROR_EXIT
:ERROR_EXIT
exit /b 1
Edit: Original idea for this came from this thread:
Okay I found the correct answer to this issue here
Here are the steps:
Now in the top row of your filtered data (just below the header) enter the following code:
=MAX($"Your Column Letter"$1:"Your Column Letter"$"The current row for the filter - 1") + 1
Ex:
=MAX($A$1:A26)+1
Which would be applied starting at cell A27.
Hold Ctrl and press enter.
Note this only works in a range, not in a table!
Also for Java 8 an interesting performance benchmark for reactive (non-blocking) Spring Boot REST application being hosted on various JVMs by AMIS Technology Blog has been published in Nov 2018 showing that, among other differences:
For details please see the source article.
Of course YMMV, this is just one of the benchmarks.
if your setup
myApp
|
|__ public
| |
| |__ stylesheets
| | |
| | |__ style.css
| |
| |___ img
| |
| |__ logo.png
|
|__ app.js
then,
put in app.js
app.use('/static', express.static('public'));
and refer to your style.css: (in some .pug file):
link(rel='stylesheet', href='/static/stylesheets/style.css')
data-src attribute is part of the data-* attributes collection introduced in HTML5. data-src allow us to store extra data that have no meaning to the browser but that can be use by Javascript Code or CSS rules.
This is an issue of selector specificity. (The selector .selected
is less specific than ul.nav li
.)
To fix, use as much specificity in the overriding rule as in the original:
ul.nav li {
background-color:blue;
}
ul.nav li.selected {
background-color:red;
}
You might also consider nixing the ul
, unless there will be other .nav
s. So:
.nav li {
background-color:blue;
}
.nav li.selected {
background-color:red;
}
That's a bit cleaner, less typing, and fewer bits.
For those coming across this and looking for performance, it looks like #delete
and #tr
are about the same in speed and 2-4x faster than gsub
.
text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04
In Java, byte
(N=8) and int
(N=32) are represented by the 2s-complement shown above.
From the equation, a7 is negative for byte
but positive for int
.
coef: a7 a6 a5 a4 a3 a2 a1 a0
Binary: 1 0 0 0 0 1 0 0
----------------------------------------------
int: 128 + 0 + 0 + 0 + 0 + 4 + 0 + 0 = 132
byte: -128 + 0 + 0 + 0 + 0 + 4 + 0 + 0 = -124
PRIMARY KEY CONSTRAINT
cannot be altered, you may only drop it and create again. For big datasets it can cause a long run time and thus - table inavailability.
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
@ubuntu 18.04
sudo apt install openjdk-8-jdk
then
sudo update-alternatives --config java
Selection Path Priority Status
------------------------------------------------------------
0 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 auto mode
1 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 manual mode
* 2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1081 manual mode
Press <enter> to keep the current choice[*], or type selection number:
choose java 8 then restart netbeans
Done
This /[^a-z]/g
solves the problem.
function pangram(str) {
let regExp = /[^a-z]/g;
let letters = str.toLowerCase().replace(regExp, '');
document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2@# %hfr efg uor7 489(*&^% knt lhtkjj ngnm!@#$%^&*()_');
_x000D_
<h4 id="letters"></h4>
_x000D_
It works, when you use both lines:
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"
Check Calendar
class. It has add
method (and some others) to allow time manipulation.
Something like this should work:
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date()); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
cal.getTime(); // returns new date object plus one hour
Check API for more.
You can use ReSharper for namespace refactoring. It will give 30 days free trial. It will change namespace as per folder structure.
Steps:
Right click on the project/folder/files you want to refactor.
If you have installed ReSharper then you will get an option Refactor->Adjust Namespaces.... So click on this.
It will automatically change the name spaces of all the selected files.
It can also be done this way:
figure(xx);
set(gcf, 'name', 'Name goes here')
gcf
gets the current figure handle.
System.Threading.Thread.Sleep(50);
Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")
Just remove the ;
to make it work for VB.net as well.
Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.
There is also a port of nano for windows, which is more more akin to notepad.exe than vim is
https://www.nano-editor.org/dist/win32-support/
Get the WINNT zip. Tested in Windows 7 works as expected
Adding to @behzad.nouri 's answer - we can create a helper routine to handle this common scenario:
def csvDf(dat,**kwargs):
from numpy import array
data = array(dat)
if data is None or len(data)==0 or len(data[0])==0:
return None
else:
return pd.DataFrame(data[1:,1:],index=data[1:,0],columns=data[0,1:],**kwargs)
Let's try it out:
data = [['','a','b','c'],['row1','row1cola','row1colb','row1colc'],
['row2','row2cola','row2colb','row2colc'],['row3','row3cola','row3colb','row3colc']]
csvDf(data)
In [61]: csvDf(data)
Out[61]:
a b c
row1 row1cola row1colb row1colc
row2 row2cola row2colb row2colc
row3 row3cola row3colb row3colc
Ajax Submit form with out page refresh by using jquery ajax method first include library jquery.js and jquery-form.js then create form in html:
<form action="postpage.php" method="POST" id="postForm" >
<div id="flash_success"></div>
name:
<input type="text" name="name" />
password:
<input type="password" name="pass" />
Email:
<input type="text" name="email" />
<input type="submit" name="btn" value="Submit" />
</form>
<script>
var options = {
target: '#flash_success', // your response show in this ID
beforeSubmit: callValidationFunction,
success: YourResponseFunction
};
// bind to the form's submit event
jQuery('#postForm').submit(function() {
jQuery(this).ajaxSubmit(options);
return false;
});
});
function callValidationFunction()
{
// validation code for your form HERE
}
function YourResponseFunction(responseText, statusText, xhr, $form)
{
if(responseText=='success')
{
$('#flash_success').html('Your Success Message Here!!!');
$('body,html').animate({scrollTop: 0}, 800);
}else
{
$('#flash_success').html('Error Msg Here');
}
}
</script>
Spinner spnLocale = (Spinner)findViewById(R.id.spnLocale);
spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Your code here
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
Note: Remember one thing.
Spinner OnItemSelectedListener
event will execute twice:
Try to differentiate those two by using flag variable.
As a newbie in React world, I came across a similar issues where I could not edit
the textarea and struggled
with binding. It's worth knowing about controlled
and uncontrolled
elements when it comes to react.
The value of the following uncontrolled textarea
cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea
can be changed because of use of defaultValue
or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea
can be changed because of how
value is mapped to a state as well as the onChange
event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind
than manual binding however, if I were to not use {(event) => this.onXXXX(event)}
then that would cause the content of textarea
to be not editable OR the event.preventDefault()
does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"
Manually wrapping in BytesIO is no longer needed since PIL >= 2.8.0. Just use Image.open(response.raw)
Adding on top of Vinícius's comment:
You should pass stream=True
as noted https://requests.readthedocs.io/en/master/user/quickstart/#raw-response-content
So
img = Image.open(requests.get(url, stream=True).raw)
Almost all of the answers here are either unnecessarily complex (glob pattern matching) or rely on additional 3rd party libraries. You can do this in 2 lines using everything Pandas and python (all versions) already have built in.
For a few files - 1 liner:
df = pd.concat(map(pd.read_csv, ['data/d1.csv', 'data/d2.csv','data/d3.csv']))
For many files:
from os import listdir
filepaths = [f for f in listdir("./data") if f.endswith('.csv')]
df = pd.concat(map(pd.read_csv, filepaths))
This pandas line which sets the df utilizes 3 things:
pd.read_csv()
) the iterable (our list) which is every csv element
in filepaths).You might also be interested in C, it will also delete the end of line like D, but additionally it will put you in Insert mode at the cursor location.
No, it's not like any of those things. It's simply the dynamic replacement of attributes at runtime.
For instance, consider a class that has a method get_data
. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it. However, in a unit test, you don't want to depend on the external data source - so you dynamically replace the get_data
method with a stub that returns some fixed data.
Because Python classes are mutable, and methods are just attributes of the class, you can do this as much as you like - and, in fact, you can even replace classes and functions in a module in exactly the same way.
But, as a commenter pointed out, use caution when monkeypatching:
If anything else besides your test logic calls get_data
as well, it will also call your monkey-patched replacement rather than the original -- which can be good or bad. Just beware.
If some variable or attribute exists that also points to the get_data
function by the time you replace it, this alias will not change its meaning and will continue to point to the original get_data
. (Why? Python just rebinds the name get_data
in your class to some other function object; other name bindings are not impacted at all.)
The show command may be what you want. Try
git show -s --format=%ci <commit>
Other formats for the date string are available as well. Check the manual page for details.
s = 'hello'
ln = len(s)
i = 1
while True:
rev = s[ln-i]
print rev,
i = i + 1
if i == ln + 1 :
break
OUTPUT :
o l l e h
The other thing to be careful about, is to use the clf
(clear figure) command when you are starting a fresh plot. Otherwise you may be plotting on a pre-existing figure (not possible with the figure
command by itself, but if you do figure(2)
there may already be a figure #2), with more than one axis, or an axis that is placed kinda funny. Use clf
to ensure that you're starting from scratch:
figure(N);
clf;
plot(something);
...
from netifaces import interfaces, ifaddresses, AF_INET
iplist = [ifaddresses(face)[AF_INET][0]["addr"] for face in interfaces() if AF_INET in ifaddresses(face)]
print(iplist)
['10.8.0.2', '192.168.1.10', '127.0.0.1']
Switch inherits CompoundButton
's attributes, so I would recommend the OnCheckedChangeListener
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
}
});
Being on jupyter notebook it works for me including the relative path only. For example:
df = pd.read_csv ('file.csv')
But, for example, in vscode I have to put the complete path:
df = pd.read_csv ('/home/code/file.csv')
I see many answer reporting for zip and rar the Media Types application/zip
and application/x-rar-compressed
, respectively.
While the former matching is correct, for the latter IANA reports here https://www.iana.org/assignments/media-types/application/vnd.rar that for rar application/x-rar-compressed
is a deprecated alias name and instead application/vnd.rar
is the official one.
So, right Media Types from IANA in 2020 are:
zip
: application/zip
rar
: application/vnd.rar
add android:textAllCaps="false"
in xml button
It's true with this issue.
A simple change in Num2 class like this:
super().__init__(num)
It works in python3.
class Num:
def __init__(self,num):
self.n1 = num
class Num2(Num):
def __init__(self,num):
super().__init__(num)
self.n2 = num*2
def show(self):
print (self.n1,self.n2)
mynumber = Num2(8)
mynumber.show()
def f(x) -> str:
return x+4
print(f(45))
# will give the result :
49
# or with other words '-> str' has NO effect to return type:
print(f(45).__class__)
<class 'int'>
So I had a similar situation with the same error. I forgot I changed the compatibility mode on my dev machine and I had a console.log command in my javascript as well. I changed compatibility mode back in IE, and removed the console.log command. No more issue.
My solution hides keyboard on outside click in any activity, with of all edit texts. Without specifying them one by one.
First add to root view of layout xml: android:clickable="true" android:focusableInTouchMode="true"
Next, create one parent Acitvity of all activities you want to hide keyboard, and specify onResume() method:
@Override
protected void onResume() {
super.onResume();
//getting Root View that gets focus
View rootView =((ViewGroup)findViewById(android.R.id.content)).
getChildAt(0);
rootView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
hideKeyboard(AbstractActivity.this);
}
}
});
}
Extend your activity with this General activity (Inheritance power !) and that's all, every time any EditText (on any extended Activity) will lose focus, keyboard will be hidden.
P.S. hideKeyboard method :
public static void hideKeyboard(Activity context) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow( context.getCurrentFocus().getWindowToken(), 0);
}
context.getCurrentFocus() doesn't need specifying specific EditText view..
For me, I had to have OpenCV (3.4.2), Py-OpenCV (3.4.2), LibOpenCV (3.4.2).
My Python was version 3.5.6 with Anaconda in Windows OS 10.
I would put an absolutely positioned, z-index: 100;
span (or spans) with the background: url("myImageWithRoundedCorners.jpg");
set on it inside the #mainWrapperDivWithBGImage
.
EDIT
I want to add the reason that your IF
statement seems to not work. When you do an EXISTS
on an aggregate, it's always going to be true
. It returns a value even if the ID
doesn't exist. Sure, it's NULL
, but its returning it. Instead, do this:
if exists(select 1 from table where id = 4)
and you'll get to the ELSE
portion of your IF
statement.
Now, here's a better, set-based solution:
update b
set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
on b.id = a.id
where
b.id = yourid
This has the benefit of being able to run on the entire table rather than individual ids.
How about HKEY_CLASSES_ROOT\Word.Application\CurVer?
Instant i = Instant.ofEpochSecond(cal.getTime);
Read more here and here
Since Java 8, there are lambda and method references:
For example, if you want a functional interface A -> B
such as:
import java.util.function.Function;
public MyClass {
public static String applyFunction(String name, Function<String,String> function){
return function.apply(name);
}
}
then you can call it like so
MyClass.applyFunction("42", str -> "the answer is: " + str);
// returns "the answer is: 42"
Also you can pass class method. Say you have:
@Value // lombok
public class PrefixAppender {
private String prefix;
public String addPrefix(String suffix){
return prefix +":"+suffix;
}
}
Then you can do:
PrefixAppender prefixAppender= new PrefixAppender("prefix");
MyClass.applyFunction("some text", prefixAppender::addPrefix);
// returns "prefix:some text"
Note:
Here I used the functional interface Function<A,B>
, but there are many others in the package java.util.function
. Most notable ones are
Supplier
: void -> A
Consumer
: A -> void
BiConsumer
: (A,B) -> void
Function
: A -> B
BiFunction
: (A,B) -> C
and many others that specialize on some of the input/output type. Then, if it doesn't provide the one you need, you can create your own functional interface like so:
@FunctionalInterface
interface Function3<In1, In2, In3, Out> { // (In1,In2,In3) -> Out
public Out apply(In1 in1, In2 in2, In3 in3);
}
Example of use:
String computeAnswer(Function3<String, Integer, Integer, String> f){
return f.apply("6x9=", 6, 9);
}
computeAnswer((question, a, b) -> question + "42");
// "6*9=42"
And you can also do that with thrown exception:
@FunctionalInterface
interface FallibleFunction<In, Out, Ex extends Exception> {
Out get(In input) throws Ex;
}
public <Ex extends IOException> String yo(FallibleFunction<Integer, String, Ex> f) throws Ex {
return f.get(42);
}
If you're getting your timestamps from System.currentTimeMillis()
, then your time variables should be longs.
For the sake of completeness, what you are trying to create is a "modal window".
Numerous JS solutions allow you to create them with ease, take the time to find the one which best suits your needs.
I have used Tinybox 2 for small projects : http://sandbox.scriptiny.com/tinybox2/
Google introduced In-app updates feature, (https://developer.android.com/guide/app-bundle/in-app-updates) it works on Lollipop+ and gives you the ability to ask the user for an update with a nice dialog (FLEXIBLE) or with mandatory full-screen message (IMMEDIATE).
Here is how Flexible update will look like:
and here is Immedtiate update flow:
You can check my answer here https://stackoverflow.com/a/56808529/5502121 to get the complete sample code of implementing both Flexible and Immediate update flows. Hope it helps!
With Guava, you can use Iterables.concat(Iterable<T> ...)
, it creates a live view of all the iterables, concatenated into one (if you change the iterables, the concatenated version also changes). Then wrap the concatenated iterable with Iterables.unmodifiableIterable(Iterable<T>)
(I hadn't seen the read-only requirement earlier).
From the Iterables.concat( .. )
JavaDocs:
Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in inputs. The input iterators are not polled until necessary. The returned iterable's iterator supports
remove()
when the corresponding input iterator supports it.
While this doesn't explicitly say that this is a live view, the last sentence implies that it is (supporting the Iterator.remove()
method only if the backing iterator supports it is not possible unless using a live view)
Sample Code:
final List<Integer> first = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 5, 6);
final List<Integer> third = Lists.newArrayList(7, 8, 9);
final Iterable<Integer> all =
Iterables.unmodifiableIterable(
Iterables.concat(first, second, third));
System.out.println(all);
third.add(9999999);
System.out.println(all);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9999999]
Edit:
By Request from Damian, here's a similar method that returns a live Collection View
public final class CollectionsX {
static class JoinedCollectionView<E> implements Collection<E> {
private final Collection<? extends E>[] items;
public JoinedCollectionView(final Collection<? extends E>[] items) {
this.items = items;
}
@Override
public boolean addAll(final Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
for (final Collection<? extends E> coll : items) {
coll.clear();
}
}
@Override
public boolean contains(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
@Override
public Iterator<E> iterator() {
return Iterables.concat(items).iterator();
}
@Override
public boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
int ct = 0;
for (final Collection<? extends E> coll : items) {
ct += coll.size();
}
return ct;
}
@Override
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(E e) {
throw new UnsupportedOperationException();
}
}
/**
* Returns a live aggregated collection view of the collections passed in.
* <p>
* All methods except {@link Collection#size()}, {@link Collection#clear()},
* {@link Collection#isEmpty()} and {@link Iterable#iterator()}
* throw {@link UnsupportedOperationException} in the returned Collection.
* <p>
* None of the above methods is thread safe (nor would there be an easy way
* of making them).
*/
public static <T> Collection<T> combine(
final Collection<? extends T>... items) {
return new JoinedCollectionView<T>(items);
}
private CollectionsX() {
}
}
If you've applied the CORS middleware and it's still not working, try this.
If the route for your API is:
Route::post("foo", "MyController"})->middleware("cors");
Then you need to change it to allow for the OPTIONS method:
Route::match(['post', 'options'], "foo", "MyController")->middleware("cors");
For Swift 5
All the above answers are correct but i have done in little different way that is according to device size. Here, in ATFontManager class, i have made default font size which is define at the top of the class as defaultFontSize, this is the font size of iphone plus and you can changed according to your requirement.
class ATFontManager: UIFont{
class func setFont( _ iPhone7PlusFontSize: CGFloat? = nil,andFontName fontN : String = FontName.helveticaNeue) -> UIFont{
let defaultFontSize : CGFloat = 16
switch ATDeviceDetector().screenType {
case .iPhone4:
if let fontSize = iPhone7PlusFontSize{
return UIFont(name: fontN, size: fontSize - 5)!
}
return UIFont(name: fontN, size: defaultFontSize - 5)!
case .iPhone5:
if let fontSize = iPhone7PlusFontSize{
return UIFont(name: fontN, size: fontSize - 3)!
}
return UIFont(name: fontN, size: defaultFontSize - 3)!
case .iPhone6AndIphone7, .iPhoneUnknownSmallSize:
if let fontSize = iPhone7PlusFontSize{
return UIFont(name: fontN, size: fontSize - 2)!
}
return UIFont(name: fontN, size: defaultFontSize - 2)!
case .iPhone6PAndIPhone7P, .iPhoneUnknownBigSize:
return UIFont(name: fontN, size: iPhone7PlusFontSize ?? defaultFontSize)!
case .iPhoneX, .iPhoneXsMax:
return UIFont(name: fontN, size: iPhone7PlusFontSize ?? defaultFontSize)!
case .iPadMini:
if let fontSize = iPhone7PlusFontSize{
return UIFont(name: fontN, size: fontSize + 2)!
}
return UIFont(name: fontN, size: defaultFontSize + 2)!
case .iPadPro10Inch:
if let fontSize = iPhone7PlusFontSize{
return UIFont(name: fontN, size: fontSize + 4)!
}
return UIFont(name: fontN, size: defaultFontSize + 4)!
case .iPadPro:
if let fontSize = iPhone7PlusFontSize{
return UIFont(name: fontN, size: fontSize + 6)!
}
return UIFont(name: fontN, size: defaultFontSize + 6)!
case .iPadUnknownSmallSize:
return UIFont(name: fontN, size: defaultFontSize + 2)!
case .iPadUnknownBigSize:
return UIFont(name: fontN, size: defaultFontSize + 4)!
default:
return UIFont(name: fontN, size: iPhone7PlusFontSize ?? 16)!
}
}
}
I have added certain font name, for more you can add the font name and type here.
enum FontName : String {
case HelveticaNeue = "HelveticaNeue"
case HelveticaNeueUltraLight = "HelveticaNeue-UltraLight"
case HelveticaNeueBold = "HelveticaNeue-Bold"
case HelveticaNeueBoldItalic = "HelveticaNeue-BoldItalic"
case HelveticaNeueMedium = "HelveticaNeue-Medium"
case AvenirBlack = "Avenir-Black"
case ArialBoldMT = "Arial-BoldMT"
case HoeflerTextBlack = "HoeflerText-Black"
case AMCAPEternal = "AMCAPEternal"
}
This class refers to device detector in order to provide appropriate font size according to device.
class ATDeviceDetector {
var iPhone: Bool {
return UIDevice().userInterfaceIdiom == .phone
}
var ipad : Bool{
return UIDevice().userInterfaceIdiom == .pad
}
let isRetina = UIScreen.main.scale >= 2.0
enum ScreenType: String {
case iPhone4
case iPhone5
case iPhone6AndIphone7
case iPhone6PAndIPhone7P
case iPhoneX
case iPadMini
case iPadPro
case iPadPro10Inch
case iPhoneOrIPadSmallSizeUnknown
case iPadUnknown
case unknown
}
struct ScreenSize{
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH,ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH,ScreenSize.SCREEN_HEIGHT)
}
var screenType: ScreenType {
switch ScreenSize.SCREEN_MAX_LENGTH {
case 0..<568.0:
return .iPhone4
case 568.0:
return .iPhone5
case 667.0:
return .iPhone6AndIphone7
case 736.0:
return .iPhone6PAndIPhone7P
case 812.0:
return .iPhoneX
case 568.0..<812.0:
return .iPhoneOrIPadSmallSizeUnknown
case 1112.0:
return .iPadPro10Inch
case 1024.0:
return .iPadMini
case 1366.0:
return .iPadPro
case 812.0..<1366.0:
return .iPadUnknown
default:
return .unknown
}
}
}
How to use. Hope it will help.
//for default
label.font = ATFontManager.setFont()
//if you want to provide as your demand. Here **iPhone7PlusFontSize** variable is denoted as font size for *iphone 7plus and iphone 6 plus*, and it **ATFontManager** class automatically handle.
label.font = ATFontManager.setFont(iPhone7PlusFontSize: 15, andFontName: FontName.HelveticaNeue.rawValue)
For the sake of completeness, let me mention that there are some places (on a Windows PC) to look for javaw.exe
in case it is not found in the path:
(Still Reimeus' suggestion should be your first attempt.)
1.
Java usually stores it's location in Registry, under the following key:
HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome
2.
Newer versions of JRE/JDK, seem to also place a copy of javaw.exe
in 'C:\Windows\System32', so one might want to check there too (although chances are, if it is there, it will be found in the path as well).
3.
Of course there are the "usual" install locations:
[Note, that for older versions of Windows (XP, Vista(?)), this will only help on english versions of the OS. Fortunately, on later version of Windows "Program Files" will point to the directory regardless of its "display name" (which is language-specific).]
A little while back, I wrote this piece of code to check for javaw.exe
in the aforementioned places. Maybe someone finds it useful:
static protected String findJavaw() {
Path pathToJavaw = null;
Path temp;
/* Check in Registry: HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome */
String keyNode = "HKLM\\Software\\JavaSoft\\Java Runtime Environment";
List<String> output = new ArrayList<>();
executeCommand(new String[] {"REG", "QUERY", "\"" + keyNode + "\"",
"/v", "CurrentVersion"},
output);
Pattern pattern = Pattern.compile("\\s*CurrentVersion\\s+\\S+\\s+(.*)$");
for (String line : output) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
keyNode += "\\" + matcher.group(1);
List<String> output2 = new ArrayList<>();
executeCommand(
new String[] {"REG", "QUERY", "\"" + keyNode + "\"",
"/v", "JavaHome"},
output2);
Pattern pattern2
= Pattern.compile("\\s*JavaHome\\s+\\S+\\s+(.*)$");
for (String line2 : output2) {
Matcher matcher2 = pattern2.matcher(line2);
if (matcher2.find()) {
pathToJavaw = Paths.get(matcher2.group(1), "bin",
"javaw.exe");
break;
}
}
break;
}
}
try {
if (Files.exists(pathToJavaw)) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
/* Check in 'C:\Windows\System32' */
pathToJavaw = Paths.get("C:\\Windows\\System32\\javaw.exe");
try {
if (Files.exists(pathToJavaw)) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
/* Check in 'C:\Program Files\Java\jre*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jre*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JRE version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files (x86)\Java\jre*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files (x86)\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jre*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JRE version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files\Java\jdk*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jdk*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JDK version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files (x86)\Java\jdk*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files (x86)\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jdk*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JDK version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
return "javaw.exe"; // Let's just hope it is in the path :)
}
If this is in fact a ListObject
table (Insert Table from the ribbon) then you can use the table's .DataBodyRange
object to get the number of rows and columns. This ignores the header row.
Sub TableTest()
Dim tbl As ListObject
Dim tRows As Long
Dim tCols As Long
Set tbl = ActiveSheet.ListObjects("Table1") '## modify to your table name.
With tbl.DataBodyRange
tRows = .Rows.Count
tCols = .Columns.Count
End With
MsgBox tbl.Name & " contains " & tRows & " rows and " & tCols & " columns.", vbInformation
End Sub
If you need to use the header row, instead of using tbl.DataBodyRange
just use tbl.Range
.
Strive to make your recursive call Tail Recursion (recursion where the last statement is the recursive call). Once you have that, converting it to iteration is generally pretty easy.
To insert a VARCHAR2
into a BLOB
column you can rely on the function utl_raw.cast_to_raw
as next:
insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));
It will cast your input VARCHAR2
into RAW
datatype without modifying its content, then it will insert the result into your BLOB
column.
More details about the function utl_raw.cast_to_raw
I was looking into this issue a bit for my own purposes; I had a slice of structs (including some pointers) and I wanted to make sure I got it right; ended up on this thread, and wanted to share my results.
To practice, I did a little go playground: https://play.golang.org/p/9i4gPx3lnY
which evals to this:
package main
import "fmt"
type Blah struct {
babyKitten int
kittenSays *string
}
func main() {
meow := "meow"
Blahs := []Blah{}
fmt.Printf("Blahs: %v\n", Blahs)
Blahs = append(Blahs, Blah{1, &meow})
fmt.Printf("Blahs: %v\n", Blahs)
Blahs = append(Blahs, Blah{2, &meow})
fmt.Printf("Blahs: %v\n", Blahs)
//fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
Blahs = nil
meow2 := "nyan"
fmt.Printf("Blahs: %v\n", Blahs)
Blahs = append(Blahs, Blah{1, &meow2})
fmt.Printf("Blahs: %v\n", Blahs)
fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
}
Running that code as-is will show the same memory address for both "meow" and "meow2" variables as being the same:
Blahs: []
Blahs: [{1 0x1030e0c0}]
Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
Blahs: []
Blahs: [{1 0x1030e0f0}]
kittenSays: nyan
which I think confirms that the struct is garbage collected. Oddly enough, uncommenting the commented print line, will yield different memory addresses for the meows:
Blahs: []
Blahs: [{1 0x1030e0c0}]
Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
kittenSays: meow
Blahs: []
Blahs: [{1 0x1030e0f8}]
kittenSays: nyan
I think this may be due to the print being deferred in some way (?), but interesting illustration of some memory mgmt behavior, and one more vote for:
[]MyStruct = nil
just Add:
<button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
Had the same problem. If server is configured correctly and .htacces is not the answer, might want to look the svg source you are embedding. Mine were created with text editor, rendered well on Chrome&Safari inside html5 code, once embedded, nothing was visible. Added correct version, dimensions etc to the svg code and works like a charm. Also, all styles inline.
Ie
<svg version="1.1" baseProfile="full" width="24" height="24" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" rx="2" ry="2" width="24" height="24" style="fill:#fbc800;width:24px;height:24px;" />
</svg>
You can use the apropos
function which is used to find the objects using partial name.
rm(list = apropos("data_"))
As others have pointed out you need the quotes, but I just want to point out that there's a shorthand method of writing this same line of code
var htmlString="<?=$htmlString?>";
See you can leave out the "php echo" stuff and replace it with a simple "=".
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
you can use the following code for getting the brand name and brand model of the device.
String brand = Build.BRAND; // for getting BrandName
String model = Build.MODEL; // for getting Model of the device
SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
SELECT MAX(p2.PAYM_DATE)
FROM user_payments as p2
WHERE p2.USER_ID = p.USER_ID
)
this's my function, convert object or array to json
function obj2json(_data){
str = '{ ';
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += "'" + i + "':" + obj2arr(v) ;
else if ($.type(v)== 'array')
str += "'" + i + "':" + obj2arr(v) ;
else{
str += "'" + i + "':'" + v + "'";
}
});
return str+= '}';
}
i just edit to v0.2 ^.^
function obj2json(_data){
str = (($.type(_data)== 'array')?'[ ': '{ ');
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += '"' + i + '":' + obj2json(v) ;
else if ($.type(v)== 'array')
str += '"' + i + '":' + obj2json(v) ;
else{
if($.type(_data)== 'array')
str += '"' + v + '"';
else
str += '"' + i + '":"' + v + '"';
}
});
return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}
What i have done is that import a new project into eclipse workspace, and that path of that was be
android-sdk-macosx/extras/google/google_play_services/libproject/google-play-services_lib
and add as library in your project.. that it .. simple!! you might require to add support library in your project.
There's a really good paper by Microsoft Research called To Blob or Not To Blob.
Their conclusion after a large number of performance tests and analysis is this:
if your pictures or document are typically below 256KB in size, storing them in a database VARBINARY column is more efficient
if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)
in between those two, it's a bit of a toss-up depending on your use
If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.
For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".
Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:
CREATE TABLE dbo.YourTable
(....... define the fields here ......)
ON Data -- the basic "Data" filegroup for the regular data
TEXTIMAGE_ON LARGE_DATA -- the filegroup for large chunks of data
Check out the MSDN intro on filegroups, and play around with it!
Just stumbled upon the same problem and most answers here seem to only solve it for Angular internal routing, and then some of them for route parameters which is not the same as request parameters.
I am guessing that I have a similar use case to the original question by Lars.
For me the use case is e.g. referral tracking:
Angular running on mycoolpage.com
, with hash routing, so mycoolpage.com
redirects to mycoolpage.com/#/
. For referral, however, a link such as mycoolpage.com?referrer=foo
should also be usable. Unfortunately, Angular immediately strips the request parameters, going directly to mycoolpage.com/#/
.
Any kind of 'trick' with using an empty component + AuthGuard and getting queryParams
or queryParamMap
did, unfortunately, not work for me. They were always empty.
My hacky solution ended up being to handle this in a small script in index.html
which gets the full URL, with request parameters. I then get the request param value via string manipulation and set it on window object. A separate service then handles getting the id from the window object.
index.html script
const paramIndex = window.location.href.indexOf('referrer=');
if (!window.myRef && paramIndex > 0) {
let param = window.location.href.substring(paramIndex);
param = param.split('&')[0];
param = param.substr(param.indexOf('=')+1);
window.myRef = param;
}
Service
declare var window: any;
@Injectable()
export class ReferrerService {
getReferrerId() {
if (window.myRef) {
return window.myRef;
}
return null;
}
}
@Inject
instead of Spring’s @Autowired
to inject a bean.
@Named
instead of Spring’s @Component
to declare a bean.
Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotation (as long as the following jar
is in your classpath)
Create a stored procedure that does something like the following:
declare @startDate date;
declare @endDate date;
select @startDate = '20150528';
select @endDate = '20150531';
with dateRange as
(
select dt = dateadd(dd, 1, @startDate)
where dateadd(dd, 1, @startDate) < @endDate
union all
select dateadd(dd, 1, dt)
from dateRange
where dateadd(dd, 1, dt) < @endDate
)
select *
from dateRange
Or better still create a calendar table and just select from that.
The else
clause is only executed when your while
condition becomes false. If you break
out of the loop, or if an exception is raised, it won't be executed.
One way to think about it is as an if/else construct with respect to the condition:
if condition:
handle_true()
else:
handle_false()
is analogous to the looping construct:
while condition:
handle_true()
else:
# condition is false now, handle and go on with the rest of the program
handle_false()
An example might be along the lines of:
while value < threshold:
if not process_acceptable_value(value):
# something went wrong, exit the loop; don't pass go, don't collect 200
break
value = update(value)
else:
# value >= threshold; pass go, collect 200
handle_threshold_reached()
I think the cleanest way is this!
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$supportedLanguages=['en','fr','gr'];
if(!in_array($lang,$supportedLanguages)){
$lang='en';
}
require("index_".$lang.".php");
Other answers work, but
To get the full/default price:
$product->get_price_html();
For my future self who comes here via Google:
train_test_split
is now in model_selection
, hence:
from sklearn.model_selection import train_test_split
# given:
# features: xs
# ground truth: ys
x_train, x_test, y_train, y_test = train_test_split(xs, ys,
test_size=0.33,
random_state=0,
stratify=ys)
is the way to use it. Setting the random_state
is desirable for reproducibility.
For posterity, I think this is quicker:
a = np.array([np.array(list()) for _ in y])
You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.
Responding to comment below:
>>> import numpy as np
>>> y = range(10)
>>> a = np.array([np.array(list) for _ in y])
>>> a
array([array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object)], dtype=object)
I've solved this error by this way.
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.someurl/' );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30);
ob_start();
$response = curl_exec ( $ch );
$data = ob_get_clean();
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200 ) success;
Error still occurs, but I can handle response data in variable.
addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));
This will add ONE class or MULTIPLE classes :
addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"
Open a command prompt as an Administrator.
Enter slmgr /upk
and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.
Enter slmgr /cpky
and wait for this to complete. This will remove the product key from the registry if it's still there.
Enter slmgr /rearm
and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.
This should put the system back to a pre-key state.
Hope this helps you out!
The problem is your angular material version, I have the same, and I have resolved this when I have installed the good version of angular material in local.
Hope it solve yours too.
@Test
public void emptyJsonParseTest() {
JsonNode emptyJsonNode = new ObjectMapper().createObjectNode();
Assert.assertTrue(emptyJsonNode.asText().isEmpty());
}
At the time of writing, most browsers did return properties in the same order as they were inserted, but it was explicitly not guaranteed behaviour so shouldn't have been relied upon.
The ECMAScript specification used to say:
The mechanics and order of enumerating the properties ... is not specified.
However in ES2015 and later non-integer keys will be returned in insertion order.
Compare them as other values:
if($array_a == $array_b) {
//they are the same
}
You can read about all array operators here:
http://php.net/manual/en/language.operators.array.php
Note for example that ===
also checks that the types and order of the elements in the arrays are the same.
The delete / drop option in operations is not present in my version.
Go to CPanel -> MySQLDatabase (icon next to PhPMyAdmin) -> check the DB to be delete -> delete.
Each thread in a Java application has its own stack. The stack is used to hold return addresses, function/method call arguments, etc. So if a thread tends to process large structures via recursive algorithms, it may need a large stack for all those return addresses and such. With the Sun JVM, you can set that size via that parameter.
So if I wanted to return a first name and last name like: Hello Fred Gerbig I would use the code below, this code works but is it actually the most correct way to do it?
import sys
def main():
if len(sys.argv) >= 2:
fname = sys.argv[1]
lname = sys.argv[2]
else:
name = 'World'
print 'Hello', fname, lname
if __name__ == '__main__':
main()
Edit: Found that the above code works with 2 arguments but crashes with 1. Tried to set len to 3 but that did nothing, still crashes (re-read the other answers and now understand why the 3 did nothing). How do I bypass the arguments if only one is entered? Or how would error checking look that returned "You must enter 2 arguments"?
Edit 2: Got it figured out:
import sys
def main():
if len(sys.argv) >= 2:
name = sys.argv[1] + " " + sys.argv[2]
else:
name = 'World'
print 'Hello', name
if __name__ == '__main__':
main()
For one, you don't seem to be including jQuery itself in the header but only a bunch of plugins. As for the '<' error, it's impossible to tell without seeing the generated HTML.
You can put your string into viewdata in controller like this :
ViewData["string"] = DBstring;
And then call that viewdata in view like this :
@Html.Raw(ViewData["string"].ToString())
Download php5.dll (http://windows.php.net/download/) and copy it to apache/bin folder. That solved it for me (Win 7 64 bit apache 32 bit)
EDIT: Start with the non-thread safe version.
You can always use multiple
or multiple = "true"
option with a select tag, but there is one jquery plugin which makes it more beautiful. It is called chosen and can be found here.
This fiddle-example might help you to get started
Thank you.
It depends which one to chose is based on the requirement
Handler is mostly used to switch from other thread to main thread, Handler is attached to a looper on which it post its runnable task in queue. So If you are already in other thread and switch to main thread then you need handle instead of async task or other thread
If Handler created in other than main thread which is not a looper is will not give error as handle is created the thread, that thread need to be made a lopper
AsyncTask is used to execute code for few seconds which run on background thread and gives its result to main thread ** *AsyncTask Limitations 1. Async Task is not attached to life cycle of activity and it keeps run even if its activity destroyed whereas loader doesn't have this limitation 2. All Async Tasks share the same background thread for execution which also impact the app performance
Thread is used in app for background work also but it doesn't have any call back on main thread. If requirement suits some threads instead of one thread and which need to give task many times then thread pool executor is better option.Eg Requirement of Image loading from multiple url like glide.
You can set the second parameter of print_r
to true
to get the output returned rather than directly printed:
$output = print_r($myarray, true);
You can use this to fit everything into one echo
(don’t forget htmlspecialchars
if you want to print it into HTML):
echo "<pre>", htmlspecialchars(print_r($myarray, true)), "</pre>";
If you then put this into a custom function, it is just as easy as using print_r
:
function printr($a) {
echo "<pre>", htmlspecialchars(print_r($a, true)), "</pre>";
}
You can link libraries from cdn (Content delivery network):
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
Or link libraries locally, add css files in the css folder and jquery in js folder. You have to keep both folders in the laravel public folder then you can link like below:
<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>
or else
{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}
If you link js files and css files locally (like in the last two examples) you need to add js
and css
files to the js
and css
folders which are in public\js
or public\css
not in resources\assets
.
Add
android:configChanges="keyboardHidden|orientation|screenSize"
to your manifest.
Add jQuery JavaScript library together with the jquery.zbox.css and jquery.zbox.js to your webpage.
<link rel="stylesheet" href="jquery.zbox.css">
<script src="jquery.min.js"></script>
<script src="jquery.zbox.min.js"></script>
Add a group of thumbnails with links pointing to the full sized images into the webpage.
<a class="zb" rel="group" href="1.png" title="Image 1">
<img src="thumb1.png">
</a>
<a class="zb" rel="group" href="2.png" title="Image 2">
<img src="thumb2.png">
</a>
<a class="zb" rel="group" href="3.png" title="Image 3">
<img src="thumb3.png">
</a>
Call the function on document ready. That's it.
In the view source do:
$(".zb").zbox();
Set also android:gravity
parameter in TextView
to center
.
For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.
Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}
You can also use the other overload, Add(string). E.g:
lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");
Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx
Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.
var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);
You can also store objects in the item's Tag property.
item2.Tag = person;
And then you can extract it
var person = item2.Tag as Person;
Let me know if you have any questions and I hope this helps!
When you call figure
, simply number the plot.
x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)
z = np.sin(x)
plt.figure(1)
plt.plot(x, z)
w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)
Edit: Note that you can number the plots however you want (here, starting from 0
) but if you don't provide figure with a number at all when you create a new one, the automatic numbering will start at 1
("Matlab Style" according to the docs).
Another clear solution, you can use constants to keep convention and add multiple [Authorize] attributes. Check this out:
public static class RolesConvention
{
public const string Administrator = "Administrator";
public const string Guest = "Guest";
}
Then in the controller:
[Authorize(Roles = RolesConvention.Administrator )]
[Authorize(Roles = RolesConvention.Guest)]
[Produces("application/json")]
[Route("api/[controller]")]
public class MyController : Controller
And then there is the original plugin ez-on-da-ice. Better yet, you can complain to me directly if there are issues. I promise you, I am mostly very responsive :).
Flags are used when an enumerable value represents a collection of enum members.
here we use bitwise operators, | and &
Example
[Flags]
public enum Sides { Left=0, Right=1, Top=2, Bottom=3 }
Sides leftRight = Sides.Left | Sides.Right;
Console.WriteLine (leftRight);//Left, Right
string stringValue = leftRight.ToString();
Console.WriteLine (stringValue);//Left, Right
Sides s = Sides.Left;
s |= Sides.Right;
Console.WriteLine (s);//Left, Right
s ^= Sides.Right; // Toggles Sides.Right
Console.WriteLine (s); //Left
You have a JSON object that contains an Array. You need to access the array results
. Change your code to:
this.data = res.json().results
@Jason-V, it really help, thanks. then, i found this examples and composed to own snippet.
#!/usr/bin/env python3
import os, readline, atexit
python_history = os.path.join(os.environ['HOME'], '.python_history')
try:
readline.read_history_file(python_history)
readline.parse_and_bind("tab: complete")
readline.set_history_length(5000)
atexit.register(readline.write_history_file, python_history)
except IOError:
pass
del os, python_history, readline, atexit
You can't use float
inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle
.
So if you want to position child
element to right of parent
element you can use margin-left: auto
but now child
element will also push other div
to the right as you can see here Fiddle
.
What you can do now is change order of elements and set order: 2
on child
element so it doesn't affect second div
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
margin-left: auto;_x000D_
order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">Ignore parent?</div>_x000D_
<div>another child</div>_x000D_
</div>
_x000D_
This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:
declare @SearchLetter2 char(2)
declare @SearchLetter char(1)
Set @SearchLetter = 'A'
Set @SearchLetter2 = @SearchLetter+'%'
select * from Customers where ContactName like @SearchLetter2 and Region='WY'
To set up an external DB and still use your local DB, you need to edit the config.inc.php file:
On Ubuntu: sudo gedit /etc/phpmyadmin/config.inc.php
The file is roughly set up like this:
if (!empty($dbname)) {
//Your local db setup
$i++;
}
What you need to do is duplicate the "your local db setup" by copying and pasting it outside of the IF
statement I've shown in the code below, and change the host to you external IP. Mine for example is:
$cfg['Servers'][$i]['host'] = '10.10.1.90:23306';
You can leave the defaults (unless you know you need to change them)
Save and refresh your PHPMYADMIN login page and a new dropdown should appear. You should be good to go.
EDIT: if you want to give the server a name to select at login page, rather than having just the IP address to select, add this to the server setup:
$cfg['Servers'][$i]['verbose'] = 'Name to show when selecting your server';
It's good if you have multiple server configs.
If you are using prototype.js then you can do this:
transport_select.observe('change', function(){
toggleSelect(transport_select_id)
})
This eliminate (as hope) the problem in cross-browsers
If you are going to call relative.py
directly and i.e. if you really want to import from a top level module you have to explicitly add it to the sys.path
list.
Here is how it should work:
# Add this line to the beginning of relative.py file
import sys
sys.path.append('..')
# Now you can do imports from one directory top cause it is in the sys.path
import parent
# And even like this:
from parent import Parent
If you think the above can cause some kind of inconsistency you can use this instead:
sys.path.append(sys.path[0] + "/..")
sys.path[0]
refers to the path that the entry point was ran from.
is a HTML entity. When doing .text()
, all HTML entities are decoded to their character values.
Instead of comparing using the entity, compare using the actual raw character:
var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
x = '';
}
Or you can also create the character from the character code manually it in its Javascript escaped form:
var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
x = '';
}
More information about String.fromCharCode
is available here:
More information about character codes for different charsets are available here:
Detecting peaks in a spectrum in a reliable way has been studied quite a bit, for example all the work on sinusoidal modelling for music/audio signals in the 80ies. Look for "Sinusoidal Modeling" in the literature.
If your signals are as clean as the example, a simple "give me something with an amplitude higher than N neighbours" should work reasonably well. If you have noisy signals, a simple but effective way is to look at your peaks in time, to track them: you then detect spectral lines instead of spectral peaks. IOW, you compute the FFT on a sliding window of your signal, to get a set of spectrum in time (also called spectrogram). You then look at the evolution of the spectral peak in time (i.e. in consecutive windows).
try like this,
ans = str.split (":");
And you can use two parts of the string like,
ans[0] and ans[1]
It's useful to look at source code sometimes.
For example findAll
implementation is very simple (vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php
):
public function findAll()
{
return $this->findBy(array());
}
So we look at findBy
and find what we need (orderBy
)
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
Output the images in a lossless format such as PNG:
ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png
Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).
I have since found that
-vsync 0
is simpler than-r 10
because it avoids needing to know the frame rate.This is something like what I currently use:
mkdir stills ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
To extract only the key frames (which are likely to be of higher quality post-edit):
ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.
It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1
and outputting as JPEG directly from ffmpeg
.
Mona is correct - Make sure that you have the task list set to show ALL as the image shows. Click the arrow to the left of the project if you want to re-factor your filter. Reset your perspective if you do not see the task list.
Sorry, but did any of the given solutions on this thread actually answer the question that was asked?
I have a String date and a date format which is different. Ex.: date: 2016-10-19 dateFormat: "DD-MM-YYYY". I need to check if this date is a valid date.
The following works for me...
const date = '2016-10-19';
const dateFormat = 'DD-MM-YYYY';
const toDateFormat = moment(new Date(date)).format(dateFormat);
moment(toDateFormat, dateFormat, true).isValid();
// Note: `new Date()` circumvents the warning that
// Moment throws (https://momentjs.com/guides/#/warnings/js-date/),
// but may not be optimal.
But honestly, don't understand why moment.isDate()
(as documented) only accepts an object. Should also support a string in my opinion.
If you removed the make all
line from your "fresh" target:
fresh :
rm -f *.o $(EXEC)
clear
You could simply run the command make fresh all
, which will execute as make fresh; make all
.
Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.
You can use a list comprehension:
x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of 'foo' (which can depend on i and j if you want)
I wanted to do something like this without making a separate function, and came up with this simple one-line approach:
DECLARE @test NVARCHAR(255)
SET @test = 'First Second'
SELECT SUBSTRING(@test,1,(CHARINDEX(' ',@test + ' ')-1))
This would return the result "First"
It's short, just not as robust, as it assumes your string doesn't start with a space. It will handle one-word inputs, multi-word inputs, and empty string or NULL inputs.
There is no difference at all!
1) git checkout -b branch origin/branch
If there is no --track
and no --no-track
, --track
is assumed as default. The default can be changed with the setting branch.autosetupmerge
.
In effect, 1) behaves like git checkout -b branch --track origin/branch
.
2) git checkout --track origin/branch
“As a convenience”, --track
without -b
implies -b
and the argument to -b
is guessed to be “branch”. The guessing is driven by the configuration variable remote.origin.fetch
.
In effect, 2) behaves like git checkout -b branch --track origin/branch
.
As you can see: no difference.
But it gets even better:
3) git checkout branch
is also equivalent to git checkout -b branch --track origin/branch
if “branch” does not exist yet but “origin/branch” does1.
All three commands set the “upstream” of “branch” to be “origin/branch” (or they fail).
Upstream is used as reference point of argument-less git status
, git push
, git merge
and thus git pull
(if configured like that (which is the default or almost the default)).
E.g. git status
tells you how far behind or ahead you are of upstream, if one is configured.
git push
is configured to push the current branch upstream by default2 since git 2.0.
1 ...and if “origin” is the only remote having “branch”
2 the default (named “simple”) also enforces for both branch names to be equal
I used this one document.querySelector('ElementClass').innerText = 'newtext';
Appears to work with span, texts within classes/buttons
Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.
As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.
Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.
Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.
import requests
import json
url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
payload = {
"Host": "www.mywbsite.fr",
"Connection": "keep-alive",
"Content-Length": 129,
"Origin": "https://www.mywbsite.fr",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
"Content-Type": "application/json",
"Accept": "*/*",
"Referer": "https://www.mywbsite.fr/data/mult.aspx",
"Accept-Encoding": "gzip,deflate,sdch",
"Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
"Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
}
# Adding empty header as parameters are being sent in payload
headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)
Only for Android
Add in your custom theme
<item name="android:colorActivatedHighlight">@android:color/transparent</item>
The Bootstrap team seems to have removed it. See here: https://github.com/twbs/bootstrap/issues/8922 . @Skelly's answer involves custom css which I didn't want to do so I used the grid system and nav-pills. It worked fine and looked great. The code looks like so:
<div class="row">
<!-- Navigation Buttons -->
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked" id="myTabs">
<li class="active"><a href="#home" data-toggle="pill">Home</a></li>
<li><a href="#profile" data-toggle="pill">Profile</a></li>
<li><a href="#messages" data-toggle="pill">Messages</a></li>
</ul>
</div>
<!-- Content -->
<div class="col-md-9">
<div class="tab-content">
<div class="tab-pane active" id="home">Home</div>
<div class="tab-pane" id="profile">Profile</div>
<div class="tab-pane" id="messages">Messages</div>
</div>
</div>
</div>
You can see this in action here: http://bootply.com/81948
[Update]
@SeanK gives the option of not having to enable the nav-pills through Javascript and instead using data-toggle="pill"
. Check it out here: http://bootply.com/96067. Thanks Sean.
You may use Map.entrySet()
method:
for (Map.Entry entry : objectSet.entrySet())
{
System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
}
I found this to finally work.
python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.12.0-py3-none-any.whl
Edit 1: This was tested on Windows (8, 8.1, 10), Mac and Linux. Change python3
to python
according to your configuration. Change py3
to py2
in the url if you are using Python 2.x.
Edit 2: A list of different versions if someone needs: https://storage.googleapis.com/tensorflow
Edit 3: A list of urls for the available wheel packages is available here: https://www.tensorflow.org/install/pip#package-location
The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.
Refer below URL
There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.
Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4
Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220
Yes you can do the following.
[[float(y) for y in x] for x in l]
Constructor of public
class clients
is public
but it has a parameter of type ACTInterface
that is private
(it is nested in a class?). You can't do that. You need to make ACTInterface
at least as accessible as clients
.
PHP does not know these Unicode escape sequences. But as unknown escape sequences remain unaffected, you can write your own function that converts such Unicode escape sequences:
function unicodeString($str, $encoding=null) {
if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
}
Or with an anonymous function expression instead of create_function
:
function unicodeString($str, $encoding=null) {
if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
}, $str);
}
Its usage:
$str = unicodeString("\u1000");
Code like this
<html>
<head>
<script type="text/javascript" src="path/to/script.js"></script>
<!--other script and also external css included over here-->
</head>
<body>
<form>
<select name="users" onChange="showUser(this.value)">
<option value="1">Tom</option>
<option value="2">Bob</option>
<option value="3">Joe</option>
</select>
</form>
</body>
</html>
I hope it will help you.... thanks
Updates according iOS7
// If description are available for protocol
protocolDescriptionLabel.text = [dataDictionary objectForKey:@"description"];
[protocolDescriptionLabel sizeToFit];
[protocolDescriptionLabel setLineBreakMode:NSLineBreakByWordWrapping];
CGSize expectedLabelSize = [protocolDescriptionLabel
textRectForBounds:protocolDescriptionLabel.frame
limitedToNumberOfLines:protocolDescriptionLabel.numberOfLines].size;
NSLog(@"expectedLabelSize %f", expectedLabelSize.height);
//adjust the label the the new height.
CGRect newFrame = protocolDescriptionLabel.frame;
newFrame.size.height = expectedLabelSize.height;
protocolDescriptionLabel.frame = newFrame;
Modify your CSS like this:
.vertical_banner {_x000D_
border: 1px solid #E9E3DD;_x000D_
float: left;_x000D_
height: 210px;_x000D_
margin: 2px;_x000D_
padding: 4px 2px 10px 10px;_x000D_
text-align: left;_x000D_
width: 117px;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
#bottom_link{_x000D_
position:absolute; /* added */_x000D_
bottom:0; /* added */_x000D_
left:0; /* added */_x000D_
}
_x000D_
<div class="vertical_banner">_x000D_
<div id="bottom_link">_x000D_
<input type="submit" value="Continue">_x000D_
</div>_x000D_
</div>
_x000D_
The code in elyase's answer https://stackoverflow.com/a/27928411/4240413 does not actually work. Notice that sse is a scalar, and then it tries to iterate through it. The following code is a modified version. Not amazingly clean, but I think it works more or less.
class LinearRegression(linear_model.LinearRegression):
def __init__(self,*args,**kwargs):
# *args is the list of arguments that might go into the LinearRegression object
# that we don't know about and don't want to have to deal with. Similarly, **kwargs
# is a dictionary of key words and values that might also need to go into the orginal
# LinearRegression object. We put *args and **kwargs so that we don't have to look
# these up and write them down explicitly here. Nice and easy.
if not "fit_intercept" in kwargs:
kwargs['fit_intercept'] = False
super(LinearRegression,self).__init__(*args,**kwargs)
# Adding in t-statistics for the coefficients.
def fit(self,x,y):
# This takes in numpy arrays (not matrices). Also assumes you are leaving out the column
# of constants.
# Not totally sure what 'super' does here and why you redefine self...
self = super(LinearRegression, self).fit(x,y)
n, k = x.shape
yHat = np.matrix(self.predict(x)).T
# Change X and Y into numpy matricies. x also has a column of ones added to it.
x = np.hstack((np.ones((n,1)),np.matrix(x)))
y = np.matrix(y).T
# Degrees of freedom.
df = float(n-k-1)
# Sample variance.
sse = np.sum(np.square(yHat - y),axis=0)
self.sampleVariance = sse/df
# Sample variance for x.
self.sampleVarianceX = x.T*x
# Covariance Matrix = [(s^2)(X'X)^-1]^0.5. (sqrtm = matrix square root. ugly)
self.covarianceMatrix = sc.linalg.sqrtm(self.sampleVariance[0,0]*self.sampleVarianceX.I)
# Standard erros for the difference coefficients: the diagonal elements of the covariance matrix.
self.se = self.covarianceMatrix.diagonal()[1:]
# T statistic for each beta.
self.betasTStat = np.zeros(len(self.se))
for i in xrange(len(self.se)):
self.betasTStat[i] = self.coef_[0,i]/self.se[i]
# P-value for each beta. This is a two sided t-test, since the betas can be
# positive or negative.
self.betasPValue = 1 - t.cdf(abs(self.betasTStat),df)
An other approach using borders and no CSS3 properties :
div, div:after{_x000D_
border-width: 80px 0 80px 80px;_x000D_
border-color: transparent transparent transparent #000;_x000D_
border-style:solid;_x000D_
position:relative;_x000D_
}_x000D_
div:after{_x000D_
content:'';_x000D_
position:absolute;_x000D_
left:-115px; top:-80px;_x000D_
border-left-color:#fff;_x000D_
}
_x000D_
<div></div>
_x000D_
There is a library called BoofCV which claims to better than ZBar and other libraries.
Here are the steps to use that (any OS).
Pre-requisites:
pip install pyboof
Class to decode:
import os
import numpy as np
import pyboof as pb
pb.init_memmap() #Optional
class QR_Extractor:
# Src: github.com/lessthanoptimal/PyBoof/blob/master/examples/qrcode_detect.py
def __init__(self):
self.detector = pb.FactoryFiducial(np.uint8).qrcode()
def extract(self, img_path):
if not os.path.isfile(img_path):
print('File not found:', img_path)
return None
image = pb.load_single_band(img_path, np.uint8)
self.detector.detect(image)
qr_codes = []
for qr in self.detector.detections:
qr_codes.append({
'text': qr.message,
'points': qr.bounds.convert_tuple()
})
return qr_codes
Usage:
qr_scanner = QR_Extractor()
output = qr_scanner.extract('Your-Image.jpg')
print(output)
Tested and works on Python 3.8 (Windows & Ubuntu)
If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"
<DataGrid IsReadOnly="True" CanUserAddRows="False" />
Further more you can set IsReadOnly on individual columns to disable editing.
That's interesting, but as far as I know the answer is a firm no. I don't see why you need a nested ID, since you'll usually cross it with another element that has the same nested ID. If you don't there's no point, if you do there's still very little point.
if you don't want to use a link, use button. you can add image to button as well:
<button type="button" onclick="location.href='@Url.Action("Create", "Company")'" >
Create New
<img alt="New" title="New" src="~/Images/Button/plus.png">
</button>
type="button" performs your action instead of submitting form.
from virtualenv's official document https://virtualenv.pypa.io/en/stable/userguide/
Removing an Environment
Removing a virtual environment is simply done by deactivating it and deleting the environment folder with all its contents:
(ENV)$ deactivate $ rm -r /path/to/ENV
In my case I had to do this
npm install @types/jquery --save-dev // install jquery type as dev dependency so TS can compile properly
npm install jquery --save // save jquery as a dependency
Then in the script file A.ts
import * as $ from "jquery";
... jquery code ...
SafeAreaLayoutGuide
is UIView
property,
The top of the safeAreaLayoutGuide indicates the unobscured top edge of the view (e.g, not behind the status bar or navigation bar, if present). Similarly for the other edges.
Use safeAreaLayoutGuide
for avoid our objects clipping/overlapping from rounded corners, navigation bars, tab bars, toolbars, and other ancestor views.
We can create safeAreaLayoutGuide
object & set object constraints respectively.
Constraints for Portrait + Landscape is -
self.edgesForExtendedLayout = []//Optional our as per your view ladder
let newView = UIView()
newView.backgroundColor = .red
self.view.addSubview(newView)
newView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let guide = self.view.safeAreaLayoutGuide
newView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
newView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
newView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
newView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
else {
NSLayoutConstraint(item: newView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: newView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: newView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
newView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Another way to do that is to use the event
object inside the attribute onclick
(without the need to add an additional argument to the function to pass the event)
function callmymethod(myVal){_x000D_
console.log(myVal);_x000D_
}
_x000D_
<a href="#link" onclick="event.preventDefault();callmymethod(24)">Call</a>
_x000D_
You can find the most up to date answer for the value in your project just execute the
mvn3 help:effective-pom
command and find the <build> ... <directory>
tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.
if you are using capacitor, upgrade to capacitor/core 2.0.1 or up in your package.json
By default i won't use a guard for this one for me it is more can i enter the route or can i leave it. It is not to share data betweenn them.
If you want to load data before we entered a route just add an resolver to this one this is also part of the Router.
As very basic example:
Resolver
import { Resolve, ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs";
import { Injectable } from "@angular/core";
import { take } from "rxjs/operators";
@Injectable()
export class UserResolver implements Resolve<User> {
constructor(
private userService: UserService,
private route: ActivatedRoute
) {}
resolve(): Observable<firebase.User> {
return this.route.params.pipe(
switchMap((params) => this.userService.fetchUser(params.user_id)),
take(1)
);
}
}
put to the router:
RouterModule.forChild([
{
path: "user/:user_id",
component: MyUserDetailPage,
resolve: {
user: UserResolver
}
}
}]
get the data in our component
ngOnInit() {
const user: firebase.User = this.activatedRoute.snapshot.data.user;
}
The downside on this approach is, he will enter the route first if he get the user data not before, this ensures the data for the user has been loaded and is ready on start of the component, but you will stay on the old page as long the data has been loaded (Loading Animation)
What exactly is OAuth (Open Authorization)?
OAuth allows notifying a resource provider (e.g. Facebook) that the resource owner (e.g. you) grants permission to a third-party (e.g. a Facebook Application) access to their information (e.g. the list of your friends).
If you read it stated as plainly, I would understand your confusion. So let's go with a concrete example: joining yet another social network!
Say you have an existing GMail account. You decide to join LinkedIn. Adding all of your many, many friends manually is tiresome and error-prone. You might get fed up half-way or insert typos in their e-mail address for invitation. So you might be tempted not to create an account after all.
Facing this situation, LinkedIn has the Good Idea(TM) to write a program that adds your list of friends automatically because computers are far more efficient and effective at tiresome and error prone tasks. Since joining the network is now so easy, there is no way you would refuse such an offer, now would you?
Without an API for exchanging this list of contacts, you would have to give LinkedIn the username and password to your GMail account, thereby giving them too much power.
This is where OAuth comes in. If your GMail supports the OAuth protocol, then LinkedIn can ask you to authorize them to access your GMail list of contacts.
OAuth allows for:
Will it become a de facto (standard?) in near future?
Well, although OAuth is a significant step forward, it doesn't solve problems if people don't use it correctly. For instance, if a resource provider gives only a single read-write access level to all your resources at once and doesn't provide mechanism for managing access, then there is no point to it. In other words, OAuth is a framework to provide authorization functionality and not just authentication.
In practice, it fits the social network model very well. It is especially popular for those social networks that want to allow third-party "plugins". This is an area where access to the resources is inherently necessary and is also inherently unreliable (i.e. you have little or no quality control over those applications).
I haven't seen so many other uses out in the wild. I mean, I don't know of an online financial advice firm that will access your bank records automatically, although it could technically be used that way.
Since the aggregates string can be longer than 4000 bytes, you can't use the LISTAGG
function. You could potentially create a user-defined aggregate function that returns a CLOB
rather than a VARCHAR2
. There is an example of a user-defined aggregate that returns a CLOB
in the original askTom discussion that Tim links to from that first discussion.
The main difference is that with a = a + b
, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b
, what it's really doing is typecasting b
to a type compatible with a
. So if you do
int a=5;
long b=10;
a+=b;
System.out.println(a);
What you're really doing is:
int a=5;
long b=10;
a=a+(int)b;
System.out.println(a);
The best way is to check the type, because undefined
/null
/false
are a tricky thing in JS.
So:
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
Note that typeof
always returns a string, and doesn't generate an error if the variable doesn't exist at all.
I tried this to fix access issues to an IIS website, which manifested as something like the following in the Event Logs ? Windows ? Application:
Log Name: Application Source: ASP.NET 4.0.30319.0 Date: 1/5/2012 4:12:33 PM Event ID: 1314 Task Category: Web Event Level: Information Keywords: Classic User: N/A Computer: SALTIIS01 Description: Event code: 4008 Event message: File authorization failed for the request. Event time: 1/5/2012 4:12:33 PM Event time (UTC): 1/6/2012 12:12:33 AM Event ID: 349fcb2ec3c24b16a862f6eb9b23dd6c Event sequence: 7 Event occurrence: 3 Event detail code: 0 Application information: Application domain: /LM/W3SVC/2/ROOT/Application/SNCDW-19-129702818025409890 Trust level: Full Application Virtual Path: /Application/SNCDW Application Path: D:\Sites\WCF\Application\SNCDW\ Machine name: SALTIIS01 Process information: Process ID: 1896 Process name: w3wp.exe Account name: iisservice Request information: Request URL: http://webservicestest/Application/SNCDW/PC.svc Request path: /Application/SNCDW/PC.svc User host address: 10.60.16.79 User: js3228 Is authenticated: True Authentication Type: Negotiate Thread account name: iisservice
In the end I had to give the Windows Everyone
group read access to that folder to get it to work properly.
head
section of your html page paste: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
and then the reference to your script eg: <script src="uploadfuntion.js"> </script>
4.Lastly you should ensure there are elements that match the selectors in the code.
May be you need Decimal
>>> from decimal import Decimal
>>> Decimal(2.675)
Decimal('2.67499999999999982236431605997495353221893310546875')
Check this source code out. All commented code – used to create a console in a Windows app. Uncommented – to hide the console in a console app. From here. (Previously here.) Project reg2run
.
// Copyright (C) 2005-2015 Alexander Batishchev (abatishchev at gmail.com)
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Reg2Run
{
static class ManualConsole
{
#region DllImport
/*
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();
*/
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
/*
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)]string fileName, [MarshalAs(UnmanagedType.I4)]int desiredAccess, [MarshalAs(UnmanagedType.I4)]int shareMode, IntPtr securityAttributes, [MarshalAs(UnmanagedType.I4)]int creationDisposition, [MarshalAs(UnmanagedType.I4)]int flagsAndAttributes, IntPtr templateFile);
*/
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern IntPtr GetStdHandle([MarshalAs(UnmanagedType.I4)]int nStdHandle);
/*
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetStdHandle(int nStdHandle, IntPtr handle);
*/
#endregion
#region Methods
/*
public static void Create()
{
var ptr = GetStdHandle(-11);
if (!AllocConsole())
{
throw new Win32Exception("AllocConsole");
}
ptr = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (!SetStdHandle(-11, ptr))
{
throw new Win32Exception("SetStdHandle");
}
var newOut = new StreamWriter(Console.OpenStandardOutput());
newOut.AutoFlush = true;
Console.SetOut(newOut);
Console.SetError(newOut);
}
*/
public static void Hide()
{
var ptr = GetStdHandle(-11);
if (!CloseHandle(ptr))
{
throw new Win32Exception();
}
ptr = IntPtr.Zero;
if (!FreeConsole())
{
throw new Win32Exception();
}
}
#endregion
}
}
save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database.
update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.
Disclaimer: This answer works, but is intended for educational purposes only. :) James Jones' solution is probably the best here and certainly the one I'd go with.
C# 4.0's dynamic
keyword makes this even easier, if less safe:
public static dynamic GetNullableValue(this IDataRecord record, string columnName)
{
var val = reader[columnName];
return (val == DBNull.Value ? null : val);
}
Now you don't need the explicit type hinting on the RHS:
int? value = myDataReader.GetNullableValue("MyColumnName");
In fact, you don't need it anywhere!
var value = myDataReader.GetNullableValue("MyColumnName");
value
will now be an int, or a string, or whatever type was returned from the DB.
The only problem is that this does not prevent you from using non-nullable types on the LHS, in which case you'll get a rather nasty runtime exception like:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot convert null to 'int' because it is a non-nullable value type
As with all code that uses dynamic
: caveat coder.
All you need to do is use getCheckedRadioButtonId()
and isChecked()
method,
if(gender.getCheckedRadioButtonId()==-1)
{
Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
}
else
{
// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
Toast.makeText(getApplicationContext(), selectedRadioButton.getText().toString()+" is selected", Toast.LENGTH_SHORT).show();
}
https://developer.android.com/guide/topics/ui/controls/radiobutton.html
You say you don't necessarily know that 'key2' is in position [1]. Well, it's not. Position 1 would be occupied by myHash[1].
You're abusing JavaScript arrays, which (like functions) allow key/value hashes. Even though JavaScript allows it, it does not give you facilities to deal with it, as a language designed for associative arrays would. JavaScript's array methods work with the numbered properties only.
The first thing you should do is switch to objects rather than arrays. You don't have a good reason to use an array here rather than an object, so don't do it. If you want to use an array, just number the elements and give up on the idea of hashes. The intent of an array is to hold information which can be indexed into numerically.
You can, of course, put a hash (object) into an array if you like.
myhash[1]={"key1","brightOrangeMonkey"};
I had the tableview contentInset set in viewDidLoad (as below) that what causing the horizontal scrolling
self.tableView.contentInset = UIEdgeInsetsMake(0, 30, 0, 0);
Check if there are any tableview contentInset set for different reasons and disable it
You have declared an array that can store 8 elements not 9.
this.posStatus = new int[8];
It means postStatus will contain 8 elements from index 0 to 7.
It appears that by default php does not log errors anywhere, the error_log
key in php.ini is commented out in all the install's I've seen.
Generally I:
locate php.ini
.Search these files for the error_reporting
value;
Which should be set to whatever amalgamation of php log levels are enough for you.,
Eg: E_ALL & ~E_DEPRECATED & ~E_STRICT
Check the error_log
value to make sure it points to an actual place and is not commented out.
The default value doesn't give a full path, only a file name, I don't know where this path resolves to normally. Probably /var/log/
.
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}
and if you don't want to load the entire list in memory and avoid blocking you may take a look at the following answer
.
There are no classes in C, so it's impossible to to write dynamic_cast in that language. C structures don't have methods (as a result, they don't have virtual methods), so there is nothing "dynamic" in it.
I know there are multiple ways to achieve this as per solutions shared above. I haven't tried all of them but some third party services lack clarity around what are all tasks being run in the background. I have achieved this through a powershell script similar to the one mentioned as windows batch file. I have scheduled it using Windows Tasks Scheduler to run every minute. This has been quite efficient and transparent so far. The advantage I have here is that I am checking the process explicitly before starting it again. This wouldn't cause much overhead to the CPU on the server. Also you don't have to explicitly place the file into the startup folders.
function CheckNodeService ()
{
$node = Get-Process node -ErrorAction SilentlyContinue
if($node)
{
echo 'Node Running'
}
else
{
echo 'Node not Running'
Start-Process "C:\Program Files\nodejs\node.exe" -ArgumentList "app.js" -WorkingDirectory "E:\MyApplication"
echo 'Node started'
}
}
CheckNodeService
Like so:
def find_and_replace(file, word, replacement):
with open(file, 'r+') as f:
text = f.read()
f.write(text.replace(word, replacement))
Try this SQLite Database Browser
See full document here. This is very simple and fast database browser for SQLite.
Also additional to what @andrewtweber suggested make sure that you don't have spaces between the KEY= and the value unless it is between quotes
.env file e.g.:
...
SITE_NAME= My website
MAIL_PORT= 587
MAIL_FROM_NAME= websitename
...
to:
...
SITE_NAME="My website"
MAIL_PORT=587
MAIL_FROM_NAME=websitename
...
This one works for me. The --no-color
part is, or can be, important if you want a plain string back.
git branch --no-color | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
Try the below code:
Sub opendfiles()
Dim myfile As Variant
Dim counter As Integer
Dim path As String
myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
MsgBox "No files selected"
End If
While counter <= UBound(myfile)
path = myfile(counter)
Workbooks.Open path
counter = counter + 1
Wend
End Sub
I had used JCL about 2 years back so cannot write a code for you but here is the idea;
again i apologize for solution without code, but i am out of touch by 2 yrs+
Checking this morning it appears it is now:
socket.close()
java.io.File
class contains four static separator variables. For better understanding, Let's understand with the help of some code
Note that all of these are final variables and system dependent.
Here is the java program to print these separator variables. FileSeparator.java
import java.io.File;
public class FileSeparator {
public static void main(String[] args) {
System.out.println("File.separator = "+File.separator);
System.out.println("File.separatorChar = "+File.separatorChar);
System.out.println("File.pathSeparator = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
}
}
Output of above program on Unix system:
File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :
Output of the program on Windows system:
File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;
To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
Here is the code snippet showing how to use separators correctly.
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
use awk
awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file file
PowerShell Core (v6+) now has a Remove-Service
cmdlet.
I don't know about plans to back-port it to Windows PowerShell, where it is not available as of v5.1.
Example:
# PowerShell *Core* only (v6+)
Remove-Service someservice
Note that invocation fails if the service doesn't exist, so to only remove it if it currently exists, you could do:
# PowerShell *Core* only (v6+)
$name = 'someservice'
if (Get-Service $name -ErrorAction Ignore) {
Remove-Service $name
}
Based on Haim's answer I created a PHP code to test and display all the differences between two databases. This will also display if a table is present in source or test databases. You have to change with your details the <> variables content.
<?php
$User = "<DatabaseUser>";
$Pass = "<DatabasePassword>";
$SourceDB = "<SourceDatabase>";
$TestDB = "<DatabaseToTest>";
$link = new mysqli( "p:". "localhost", $User, $Pass, "" );
if ( mysqli_connect_error() ) {
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
mysqli_set_charset( $link, "utf8" );
mb_language( "uni" );
mb_internal_encoding( "UTF-8" );
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';
$SourceDB_Content = query( $link, $sQuery );
if ( !is_array( $SourceDB_Content) ) {
echo "Table $SourceDB cannot be accessed";
exit(0);
}
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';
$TestDB_Content = query( $link, $sQuery );
if ( !is_array( $TestDB_Content) ) {
echo "Table $TestDB cannot be accessed";
exit(0);
}
$SourceDB_Tables = array();
foreach( $SourceDB_Content as $item ) {
$SourceDB_Tables[] = $item["TABLE_NAME"];
}
$TestDB_Tables = array();
foreach( $TestDB_Content as $item ) {
$TestDB_Tables[] = $item["TABLE_NAME"];
}
//var_dump( $SourceDB_Tables, $TestDB_Tables );
$LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
$NoOfDiscrepancies = 0;
echo "
<table border='1' width='100%'>
<tr>
<td>Table</td>
<td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
<td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
<td>Test result</td>
<tr>
";
foreach( $LookupTables as $table ) {
$FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
$FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
echo "
<tr>
<td>$table</td>
<td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td>
<td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>
<td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>
</tr>
";
}
echo "
</table>
<br><br>
No of discrepancies found: $NoOfDiscrepancies
";
function query( $link, $q ) {
$result = mysqli_query( $link, $q );
$errors = mysqli_error($link);
if ( $errors > "" ) {
echo $errors;
exit(0);
}
if( $result == false ) return false;
else if ( $result === true ) return true;
else {
$rset = array();
while ( $row = mysqli_fetch_assoc( $result ) ) {
$rset[] = $row;
}
return $rset;
}
}
function compareTables( $source, $test, $table ) {
global $link;
global $NoOfDiscrepancies;
$sQuery = "
SELECT column_name,ordinal_position,data_type,column_type FROM
(
SELECT
column_name,ordinal_position,
data_type,column_type,COUNT(1) rowcount
FROM information_schema.columns
WHERE
(
(table_schema='$source' AND table_name='$table') OR
(table_schema='$test' AND table_name='$table')
)
AND table_name IN ('$table')
GROUP BY
column_name,ordinal_position,
data_type,column_type
HAVING COUNT(1)=1
) A;
";
$result = query( $link, $sQuery );
$data = "";
if( is_array( $result ) && count( $result ) > 0 ) {
$NoOfDiscrepancies++;
$data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";
foreach( $result as $item ) {
$data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";
}
$data .= "</table>";
return $data;
}
else {
return "Checked but no discrepancies found!";
}
}
?>
Based on this viedo: VB.net-Auto generate row number to datagridview in windows application-winforms, you can set the DataSource and this code puts the rows numbers, works like a charm.
private void DataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// Add row number
(sender as DataGridView).Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex+1).ToString();
}