WinError 2 The system cannot find the file specified (Python)
thank you, your first error guides me here and the solution solve mine too!
for permission error, f = open('output', 'w+')
, change it into f = open(output+'output', 'w+')
.
or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.
for sure, you could probably running python/your script as administrator to pass permission error though
Python Selenium Chrome Webdriver
Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.
Step by step:
1. pip install chromedriver-binary
2. import the package
from selenium import webdriver
import chromedriver_binary # Adds chromedriver binary to path
driver = webdriver.Chrome()
driver.get("http://www.python.org")
Reference: https://pypi.org/project/chromedriver-binary/
selenium - chromedriver executable needs to be in PATH
Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just
driver= webdriver.Chrome()
will work
Can testify that this also works for Python3.7.
Selenium using Python - Geckodriver executable needs to be in PATH
from webdriverdownloader import GeckoDriverDownloader # vs ChromeDriverDownloader vs OperaChromiumDriverDownloader
gdd = GeckoDriverDownloader()
gdd.download_and_install()
#gdd.download_and_install("v0.19.0")
This will get you the path to your gekodriver.exe on Windows.
from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'C:\\Users\\username\\\bin\\geckodriver.exe')
driver.get('https://www.amazon.com/')
Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied
Even you run from Administrator, it may not solve the issue if the pip is installed inside another userspace. This is because Administrator doesn't own another's userspace directory, thus he can't see (go inside) the inside of the directory that is owned by somebody. Below is an exact solution.
python -m pip install -U pip --user //In Windows
Note: You should provide --user option
pip install -U pip --user //Linux, and MacOS
Install Visual Studio 2013 on Windows 7
Supported Operating Systems:
- Windows 8.1 (x86 and x64)
- Windows 8 (x86 and x64)
- Windows 7 SP1 (x86 and x64)
- Windows Server 2012 R2 (x64)
- Windows Server 2012 (x64)
- Windows Server 2008 R2 SP1 (x64)
Hardware requirements:
- 1.6 GHz or faster processor
- 1 GB of RAM (1.5 GB if running on a virtual machine)
- 20 GB of available hard disk space
- 5400 RPM hard disk drive
- DirectX 9-capable video card that runs at 1024 x 768 or higher display resolution
Additional Requirements for the laptop:
- Internet Explorer 10
- KB2883200 (available through Windows Update) is required
And don't forget to reboot after updating your windows
SQL Server: how to create a stored procedure
Try this:
create procedure dept_count(@dept_name varchar(20),@d_count int)
begin
set @d_count=(select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name)
Select @d_count as count
end
Or
create procedure dept_count(@dept_name varchar(20))
begin
select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name
end
Closing Bootstrap modal onclick
You can hide the modal and popup the window to review the carts in validateShipping() function itself.
function validateShipping(){
...
...
$('#product-options').modal('hide');
//pop the window to select items
}
Error in eval(expr, envir, enclos) : object not found
Don't know why @Janos deleted his answer, but it's correct: your data frame Train
doesn't have a column named pre
. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train
has columns called residual.sugar
, total.sulfur
, alcohol
and quality
. You need to change either your formula or your data frame so they're consistent with each other.
And just to clarify: Pre
is an object containing a formula. That formula contains a reference to the variable pre
. It's the latter that has to be consistent with the data frame.
How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?
I'd try something like:
#!/usr/bin/python
from __future__ import print_function
import shlex
from subprocess import Popen, PIPE
def shlep(cmd):
'''shlex split and popen
'''
parsed_cmd = shlex.split(cmd)
## if parsed_cmd[0] not in approved_commands:
## raise ValueError, "Bad User! No output for you!"
proc = Popen(parsed_command, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
return (proc.returncode, out, err)
... In other words let shlex.split() do most of the work. I would NOT attempt to parse the shell's command line, find pipe operators and set up your own pipeline. If you're going to do that then you'll basically have to write a complete shell syntax parser and you'll end up doing an awful lot of plumbing.
Of course this raises the question, why not just use Popen with the shell=True (keyword) option? This will let you pass a string (no splitting nor parsing) to the shell and still gather up the results to handle as you wish. My example here won't process any pipelines, backticks, file descriptor redirection, etc that might be in the command, they'll all appear as literal arguments to the command. Thus it is still safer then running with shell=True ... I've given a silly example of checking the command against some sort of "approved command" dictionary or set --- through it would make more sense to normalize that into an absolute path unless you intend to require that the arguments be normalized prior to passing the command string to this function.
Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?
Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:
You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.
Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.
-onedaywhen yesterday
Here is an example where #table constraints can prevent bad data which is not the case in CTE's
DECLARE @BadData TABLE (
ThisID int
, ThatID int );
INSERT INTO @BadData
( ThisID
, ThatID
)
VALUES
( 1, 1 ),
( 1, 2 ),
( 2, 2 ),
( 1, 1 );
IF OBJECT_ID('tempdb..#This') IS NOT NULL
DROP TABLE #This;
CREATE TABLE #This (
ThisID int NOT NULL
, ThatID int NOT NULL
UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
AS (SELECT *
FROM @BadData)
SELECT *
FROM This_CTE;
How to add a new column to a CSV file?
This code will suffice your request and I have tested on the sample code.
import csv
with open(in_path, 'r') as f_in, open(out_path, 'w') as f_out:
csv_reader = csv.reader(f_in, delimiter=';')
writer = csv.writer(f_out)
for row in csv_reader:
writer.writerow(row + [row[0]]
unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)
OK, first of all, you don't have to get a reference to the module into a different name; you already have a reference (from the import
) and you can just use it. If you want a different name just use import swineflu as f
.
Second, you are getting a reference to the class rather than instantiating the class.
So this should be:
import swineflu
fibo = swineflu.fibo() # get an instance of the class
fibo.f() # call the method f of the instance
A bound method is one that is attached to an instance of an object. An unbound method is, of course, one that is not attached to an instance. The error usually means you are calling the method on the class rather than on an instance, which is exactly what was happening in this case because you hadn't instantiated the class.
How do I show a console output/window in a forms application?
this one should work.
using System.Runtime.InteropServices;
private void Form1_Load(object sender, EventArgs e)
{
AllocConsole();
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
How to compile Go program consisting of multiple files?
Yup! That's very straight forward and that's where the package strategy comes into play. there are three ways to my knowledge.
folder structure:
GOPATH/src/
github.com/
abc/
myproject/
adapter/
main.go
pkg1
pkg2
warning: adapter can contain package main only and sun directories
- navigate to "adapter" folder. Run:
go build main.go
- navigate to "adapter" folder. Run:
go build main.go
- navigate to GOPATH/src
recognize relative path to package main, here "myproject/adapter". Run:
go build myproject/adapter
exe file will be created at the directory you are currently at.
How to export non-exportable private key from store
You might need to uninstall antivirus (in my case I had to get rid of Avast).
This makes sure that crypto::cng
command will work. Otherwise it was giving me errors:
mimikatz $ crypto::cng
ERROR kull_m_patch_genericProcessOrServiceFromBuild ; OpenProcess (0x00000005)
After removing Avast:
mimikatz $ crypto::cng
"KeyIso" service patched
Magic. (:
BTW
Windows Defender is another program blocking the program to work, so you will need also to disable it for the time of using program at least.
if (boolean == false) vs. if (!boolean)
- Here its more about the coding style
than being the functionality....
- The 1st option is very clear, but then the 2nd one is quite elegant... no offense, its just my view..
Margin between items in recycler view Android
I made a class to manage this issue. This class set different margins for the items inside the recyclerView: only the first row will have a top margin and only the first column will have left margin.
public class RecyclerViewMargin extends RecyclerView.ItemDecoration {
private final int columns;
private int margin;
/**
* constructor
* @param margin desirable margin size in px between the views in the recyclerView
* @param columns number of columns of the RecyclerView
*/
public RecyclerViewMargin(@IntRange(from=0)int margin ,@IntRange(from=0) int columns ) {
this.margin = margin;
this.columns=columns;
}
/**
* Set different margins for the items inside the recyclerView: no top margin for the first row
* and no left margin for the first column.
*/
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildLayoutPosition(view);
//set right margin to all
outRect.right = margin;
//set bottom margin to all
outRect.bottom = margin;
//we only add top margin to the first row
if (position <columns) {
outRect.top = margin;
}
//add left margin only to the first column
if(position%columns==0){
outRect.left = margin;
}
}
}
you can set it in your recyclerview this way
RecyclerViewMargin decoration = new RecyclerViewMargin(itemMargin, numColumns);
recyclerView.addItemDecoration(decoration);
Wi-Fi Direct and iOS Support
The official list of current iOS Wi-Fi Management APIs
There is no Wi-Fi Direct type of connection available. The primary issue being that Apple does not allow programmatic setting of the Wi-Fi network SSID and password. However, this improves substantially in iOS 11 where you can at least prompt the user to switch to another WiFi network.
QA1942 - iOS Wi-Fi Management APIs
Entitlement option
This technology is useful if you want to provide a list of Wi-Fi networks that a user might want to connect to in a manager type app. It requires that you apply for this entitlement with Apple and the email address is in the documentation.
MFi Program options
These technologies allow the accessory connect to the same network as the iPhone and are not for setting up a peer-to-peer connection.
- Wireless Accessory Configuration (WAC)
- HomeKit
Peer-to-peer between Apple devices
These APIs come close to what you want, but they're Apple-to-Apple only.
WiTap Example Code
iOS 11 NEHotspotConfiguration
Brought up at WWDC 2017 Advances in Networking, Part 1 is NEHotspotConfiguration which allows the app to specify and prompt to connect to a specific network.
QED symbol in latex
I think you are looking for this:
\newcommand*{\QEDA}{\hfill\ensuremath{\blacksquare}}
Usage:
\begin{example}
blah blah blah \QEDA
\end{example}
Jackson - best way writes a java list to a json array
In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.
List<Apartment> aptList = new ArrayList<Apartment>();
Apartment aptmt = null;
for(int i=0;i<5;i++){
aptmt= new Apartment();
aptmt.setAptName("Apartment Name : ArrowHead Ranch");
aptmt.setAptNum("3153"+i);
aptmt.setPhase((i+1));
aptmt.setFloorLevel(i+2);
aptList.add(aptmt);
}
mapper.writeValueAsString(aptList)
Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25
For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:
import javax.mail.*
import javax.mail.internet.*
private class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication('[email protected]', 'test1234');
}
}
def d_email = "[email protected]",
d_uname = "email",
d_password = "password",
d_host = "smtp.gmail.com",
d_port = "465", //465,587
m_to = "[email protected]",
m_subject = "Testing",
m_text = "Hey, this is the testing email."
def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")
def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);
def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Java sending and receiving file (byte[]) over sockets
The correct way to copy a stream in Java is as follows:
int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Wish I had a dollar for every time I've posted that in a forum.
How to reload a page after the OK click on the Alert Page
Confirm gives you chance to click on cancel, and reload will not be done!
Instead, you can use something like this:
if(alert('Alert For your User!')){}
else window.location.reload();
This will display alert to your user, and when he clicks OK, it will return false and reload will be done! :)
Also, the shorter version:
if(!alert('Alert For your User!')){window.location.reload();}
I hope that this helped!? :)
Find max and second max salary for a employee table MySQL
For unique salaries (i.e. first can't be same as second):
SELECT
MAX( s.salary ) AS max_salary,
(SELECT
MAX( salary )
FROM salaries
WHERE salary <> MAX( s.salary )
ORDER BY salary DESC
LIMIT 1
) AS 2nd_max_salary
FROM salaries s
And also because it's such an unnecessary way to go about solving this problem (Can anyone say 2 rows instead of 2 columns, LOL?)
How to create full path with node's fs.mkdirSync?
You can use the next function
const recursiveUpload = (path: string) => {
const paths = path.split("/")
const fullPath = paths.reduce((accumulator, current) => {
fs.mkdirSync(accumulator)
return `${accumulator}/${current}`
})
fs.mkdirSync(fullPath)
return fullPath
}
So what it does:
- Create
paths
variable, where it stores every path by itself as an element of the array.
- Adds "/" at the end of each element in the array.
- Makes for the cycle:
- Creates a directory from the concatenation of array elements which indexes are from 0 to current iteration. Basically, it is recursive.
Hope that helps!
By the way, in Node v10.12.0 you can use recursive path creation by giving it as the additional argument.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
https://nodejs.org/api/fs.html#fs_fs_mkdirsync_path_options
Convert Rtf to HTML
UPDATED:
I got home and tried the below code and it does not work. For anyone wondering, the clipboard does not just magically convert stuff like I'd hoped. Rather, it allows an application to sort of "upload" a data object with a variety of paste formats, and then then you paste (which in my metaphor would be the "download") the program being pasted into specifies its preferred format. I personally ended up using this code, which has been recommended previously, and it was enormously easy to use and very effective. After you have imported the code (in VStudio, Project -> Add Existing Files) you then just go html to rtf like this:
return HtmlToRtfConverter.ConvertHtmlToRtf(myRtfString);
or the opposite direction:
return RtfToHtmlConverter.ConvertHtmlToRtf(myHtmlString);
(below is my previous incorrect answer, in case anyone is interested in the chronology of this answer haha)
Most if not all of the above answers provide comprehensive, often Library-based solutions to the problem at hand.
I am away from my computer and thus cannot test the idea, but one alternative, cheap and vaguely hack-y method would be the following.
private string HTMLFromRtf(string rtfString)
{
Clipboard.SetData(DataFormats.Rtf, rtfString);
return Clipboard.GetData(DataFormats.Html);
}
Again, not totally sure if this would work, but just messing around with some html on my iPhone I suspect it would. Documentation is here. More in depth explanation/docs RE the getting and setting of data models in the clipboard can be found here.
(Yes I am fully aware I'm here years later, but I assume this question is one which some people still want answered).
Labeling file upload button
I could achieve a button using jQueryMobile with following code:
<label for="ppt" data-role="button" data-inline="true" data-mini="true" data-corners="false">Upload</label>
<input id="ppt" type="file" name="ppt" multiple data-role="button" data-inline="true" data-mini="true" data-corners="false" style="opacity: 0;"/>
Above code creates a "Upload" button (custom text). On click of upload button, file browse is launched. Tested with Chrome 25 & IE9.
Get width height of remote image from url
ES6: Using async/await
you can do below getMeta
function in sequence-like way and you can use it as follows (which is almost identical to code in your question (I add await
keyword and change variable end
to img
, and change var
to let
keyword). You need to run getMeta
by await
only from async
function (run).
_x000D_
_x000D_
function getMeta(url) {
return new Promise((resolve, reject) => {
let img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject();
img.src = url;
});
}
async function run() {
let img = await getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");
let w = img.width;
let h = img.height;
size.innerText = `width=${w}px, height=${h}px`;
size.appendChild(img);
}
run();
_x000D_
<div id="size" />
_x000D_
_x000D_
_x000D_
How to create a table from select query result in SQL Server 2008
use SELECT...INTO
The SELECT INTO statement creates a new table and populates it with
the result set of the SELECT statement. SELECT INTO can be used to
combine data from several tables or views into one table. It can also
be used to create a new table that contains data selected from a
linked server.
Example,
SELECT col1, col2 INTO #a -- <<== creates temporary table
FROM tablename
Standard Syntax,
SELECT col1, ....., col@ -- <<== select as many columns as you want
INTO [New tableName]
FROM [Source Table Name]
How do I skip an iteration of a `foreach` loop?
You want:
foreach (int number in numbers) // <--- go back to here --------+
{ // |
if (number < 0) // |
{ // |
continue; // Skip the remainder of this iteration. -----+
}
// do work
}
Here's more about the continue
keyword.
Update: In response to Brian's follow-up question in the comments:
Could you further clarify what I would do if I had nested for loops, and wanted to skip the iteration of one of the extended ones?
for (int[] numbers in numberarrays) {
for (int number in numbers) { // What to do if I want to
// jump the (numbers/numberarrays)?
}
}
A continue
always applies to the nearest enclosing scope, so you couldn't use it to break out of the outermost loop. If a condition like that arises, you'd need to do something more complicated depending on exactly what you want, like break
from the inner loop, then continue
on the outer loop. See here for the documentation on the break
keyword. The break
C# keyword is similar to the Perl last
keyword.
Also, consider taking Dustin's suggestion to just filter out values you don't want to process beforehand:
foreach (var basket in baskets.Where(b => b.IsOpen())) {
foreach (var fruit in basket.Where(f => f.IsTasty())) {
cuteAnimal.Eat(fruit); // Om nom nom. You don't need to break/continue
// since all the fruits that reach this point are
// in available baskets and tasty.
}
}
413 Request Entity Too Large - File Upload Issue
First edit the Nginx configuration file (nginx.conf
)
Location: sudo nano /etc/nginx/nginx.conf
Add following codes:
http {
client_max_body_size 100M;
}
Then Add the following lines in PHP configuration file(php.ini
)
Location: sudo gedit /etc/php5/fpm/php.ini
Add following codes:
memory_limit = 128M
post_max_size = 20M
upload_max_filesize = 10M
Creating a new empty branch for a new project
Let's say you have a master
branch with files/directories:
> git branch
master
> ls -la # (files and dirs which you may keep in master)
.git
directory1
directory2
file_1
..
file_n
Step by step how to make an empty branch:
git checkout —orphan new_branch_name
- Make sure you are in the right directory before executing the following command:
ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_
git rm -rf .
touch new_file
git add new_file
git commit -m 'added first file in the new branch'
git push origin new_branch_name
In step 2, we simply remove all the files locally to avoid confusion with the files on your new branch and those ones you keep in master
branch.
Then, we unlink all those files in step 3. Finally, step 4 and after are working with our new empty branch.
Once you're done, you can easily switch between your branches:
git checkout master
git checkout new_branch
Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding
Concepts
Observables in short tackles asynchronous processing and events. Comparing to promises this could be described as observables = promises + events.
What is great with observables is that they are lazy, they can be canceled and you can apply some operators in them (like map
, ...). This allows to handle asynchronous things in a very flexible way.
A great sample describing the best the power of observables is the way to connect a filter input to a corresponding filtered list. When the user enters characters, the list is refreshed. Observables handle corresponding AJAX requests and cancel previous in-progress requests if another one is triggered by new value in the input. Here is the corresponding code:
this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
(textValue
is the control associated with the filter input).
Here is a wider description of such use case: How to watch for form changes in Angular 2?.
There are two great presentations at AngularConnect 2015 and EggHead:
Christoph Burgdorf also wrote some great blog posts on the subject:
In action
In fact regarding your code, you mixed two approaches ;-) Here are they:
Manage the observable by your own. In this case, you're responsible to call the subscribe
method on the observable and assign the result into an attribute of the component. You can then use this attribute in the view for iterate over the collection:
@Component({
template: `
<h1>My Friends</h1>
<ul>
<li *ngFor="#frnd of result">
{{frnd.name}} is {{frnd.age}} years old.
</li>
</ul>
`,
directive:[CORE_DIRECTIVES]
})
export class FriendsList implement OnInit, OnDestroy {
result:Array<Object>;
constructor(http: Http) {
}
ngOnInit() {
this.friendsObservable = http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result = result);
}
ngOnDestroy() {
this.friendsObservable.dispose();
}
}
Returns from both get
and map
methods are the observable not the result (in the same way than with promises).
Let manage the observable by the Angular template. You can also leverage the async
pipe to implicitly manage the observable. In this case, there is no need to explicitly call the subscribe
method.
@Component({
template: `
<h1>My Friends</h1>
<ul>
<li *ngFor="#frnd of (result | async)">
{{frnd.name}} is {{frnd.age}} years old.
</li>
</ul>
`,
directive:[CORE_DIRECTIVES]
})
export class FriendsList implement OnInit {
result:Array<Object>;
constructor(http: Http) {
}
ngOnInit() {
this.result = http.get('friends.json')
.map(response => response.json());
}
}
You can notice that observables are lazy. So the corresponding HTTP request will be only called once a listener with attached on it using the subscribe
method.
You can also notice that the map
method is used to extract the JSON content from the response and use it then in the observable processing.
Hope this helps you,
Thierry
How can I generate a random number in a certain range?
So you would want the following:
int random;
int max;
int min;
...somewhere in your code put the method to get the min and max from the user when they click submit and then use them in the following line of code:
random = Random.nextInt(max-min+1)+min;
This will set random to a random number between the user selected min and max.
Then you will do:
TextView.setText(random.toString());
how to fetch array keys with jQuery?
Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way
var foo = {};
foo['alfa'] = "first item";
foo['beta'] = "second item";
for (var key in foo) {
console.log(key);
}
Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.
EDIT:
In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -
How to set password for Redis?
open redis configuration file
sudo nano /etc/redis/redis.conf
set passphrase
replace
# requirepass foobared
with
requirepass YOURPASSPHRASE
restart redis
redis-server restart
Why does Java have an "unreachable statement" compiler error?
It is Nanny.
I feel .Net got this one right - it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code).
Best Practice: Initialize JUnit class fields in setUp() or at declaration?
I started digging myself and I found one potential advantage of using setUp()
. If any exceptions are thrown during the execution of setUp()
, JUnit will print a very helpful stack trace. On the other hand, if an exception is thrown during object construction, the error message simply says JUnit was unable to instantiate the test case and you don't see the line number where the failure occurred, probably because JUnit uses reflection to instantiate the test classes.
None of this applies to the example of creating an empty collection, since that will never throw, but it is an advantage of the setUp()
method.
How to hide column of DataGridView when using custom DataSource?
I have noticed that if utilised progrmmatically it renders incomplete (entire form simply doesn't "paint" anything) if used before panel1.Controls.Add(dataGridView);
then dataGridView.Columns["ID"].Visible = false;
will break the entire form and make it blank, so to get round that set this AFTER EG:
panel1.Controls.Add(dataGridView);
dataGridView.Columns["ID"].Visible = false;
//works
dataGridView.Columns["ID"].Visible = false;
panel1.Controls.Add(dataGridView);
//fails miserably
Downloading jQuery UI CSS from Google's CDN
I would think so. Why not? Wouldn't be much of a CDN w/o offering the CSS to support the script files
This link suggests that they are:
We find it particularly exciting that
the jQuery UI CSS themes are now
hosted on Google's Ajax Libraries CDN.
How to disable JavaScript in Chrome Developer Tools?
Update August 2020
- Developer Tools (F12)
- Click the Gear icon
- Should open the Preference tab
- Disable Javascript option is on the far right
Original answer
- Developer Tools (F12)
- Three vertical dots in upper right
- Settings
- Under the "Preferences" tab on the left
- There will be a "Debugger" section with the option (probably on far right)
Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""
On Windows at least, pip
stores the execution path in the executable pip.exe
when it is installed.
Edit this file using a hex editor or WordPad (you have to save it as plain text then to retain binary data), change the path to Python with quotes and spaces like this:
#!"C:\Program Files (x86)\Python33\python.exe"
to an escaped path without spaces and quotes and pad with spaces (dots at the end should be spaces):
#!C:\Progra~2\Python33\python.exe.............
For "C:\Program Files", this path would probably be "C:\Progra~1" (shortened path names in DOS / Windows 3.x notation use tilde and numbers).
Windows provides this alternative notation for backwards compatibility with DOS / Windows 3.x apps.
Note that as this is a binary file, you should not change the file size which may break the executable, hence the padding.
Save with administrator privileges, make sure it is actually saved at the target location and try again.
You might also need to set the PATH
variable to use the ~
notation for the path to pip
.
How to create a new text file using Python
# Method 1
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name) # Write inside file
f.close() # Close file
# Method 2
with open("Path/To/Your/File.txt", "w") as f: # Opens file and casts as f
f.write("Hello World form " + f.name) # Writing
# File closed automatically
There are many more methods but these two are most common. Hope this helped!
Generating a WSDL from an XSD file
You cannot - a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.
These are really two separate, distinctive parts of the equation. For simplicity's sake you would often import your XSD definitions into the WSDL in the <wsdl:types>
tag.
(thanks to Cheeso for pointing out my inaccurate usage of terms)
Pure CSS collapse/expand div
Using <summary>
and <details>
Using <summary>
and <details>
elements is the simplest but see browser support as current IE is not supporting it. You can polyfill though (most are jQuery-based). Do note that unsupported browser will simply show the expanded version of course, so that may be acceptable in some cases.
_x000D_
_x000D_
/* Optional styling */_x000D_
summary::-webkit-details-marker {_x000D_
color: blue;_x000D_
}_x000D_
summary:focus {_x000D_
outline-style: none;_x000D_
}
_x000D_
<details>_x000D_
<summary>Summary, caption, or legend for the content</summary>_x000D_
Content goes here._x000D_
</details>
_x000D_
_x000D_
_x000D_
See also how to style the <details>
element (HTML5 Doctor) (little bit tricky).
Pure CSS3
The :target
selector has a pretty good browser support, and it can be used to make a single collapsible element within the frame.
_x000D_
_x000D_
.details,_x000D_
.show,_x000D_
.hide:target {_x000D_
display: none;_x000D_
}_x000D_
.hide:target + .show,_x000D_
.hide:target ~ .details {_x000D_
display: block;_x000D_
}
_x000D_
<div>_x000D_
<a id="hide1" href="#hide1" class="hide">+ Summary goes here</a>_x000D_
<a id="show1" href="#show1" class="show">- Summary goes here</a>_x000D_
<div class="details">_x000D_
Content goes here._x000D_
</div>_x000D_
</div>_x000D_
<div>_x000D_
<a id="hide2" href="#hide2" class="hide">+ Summary goes here</a>_x000D_
<a id="show2" href="#show2" class="show">- Summary goes here</a>_x000D_
<div class="details">_x000D_
Content goes here._x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to save final model using keras?
Generally, we save the model and weights in the same file by calling the save()
function.
For saving,
model.compile(optimizer='adam',
loss = 'categorical_crossentropy',
metrics = ["accuracy"])
model.fit(X_train, Y_train,
batch_size = 32,
epochs= 10,
verbose = 2,
validation_data=(X_test, Y_test))
#here I have use filename as "my_model", you can choose whatever you want to.
model.save("my_model.h5") #using h5 extension
print("model saved!!!")
For Loading the model,
from keras.models import load_model
model = load_model('my_model.h5')
model.summary()
In this case, we can simply save and load the model without re-compiling our model again.
Note - This is the preferred way for saving and loading your Keras model.
Parser Error when deploy ASP.NET application
Interesting all the different scenarios..
In my case...I had uploaded my site to GoDaddy and was getting the Parser Error.
I resolved it by commenting out compilers
under system.codedom
in web.config.
And also add a custom profile for publishing that would precompile during publishing.
<system.codedom>
<!--GoDaddy does not compile!-->
<!--<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>-->
</system.codedom>
How to automate drag & drop functionality using Selenium WebDriver Java
I would do it like this in Perl using Selenium::Remote::Driver.
my $sel = <>; #selenium handle
my $from_loc = <fromloc>;
my $to_loc = <toloc>;
my $from_element = $sel->find_element($from_loc);
my $to_element = $sel->find_element($to_loc);
# Move mouse to from element, drag and drop
$sel->mouse_move_to_location(element=>$from_element);
$sel->button_down(); # Holds the mouse button on the element
$sel->mouse_move_to_location(element=>$to); # Move mouse to the destination
$sel->button_up();
This should do it!
System.web.mvc missing
I have the same situation: Visual Studio 2010, no NuGet installed, and an ASP.NET application using System.Web.Mvc version 3.
What worked for me, was to set each C# project that uses System.Web.Mvc, to go to References in the Solution Explorer, and set properties on System.Web.Mvc, with Copy Local to true, and Specific Version to false - the last one caused the Version field to show the current version on that machine.
recursion versus iteration
Question :
And if recursion is usually slower what is the technical reason for ever using it over for loop iteration?
Answer :
Because in some algorithms are hard to solve it iteratively. Try to solve depth-first search in both recursively and iteratively. You will get the idea that it is plain hard to solve DFS with iteration.
Another good thing to try out : Try to write Merge sort iteratively. It will take you quite some time.
Question :
Is it correct to say that everywhere recursion is used a for loop could be used?
Answer :
Yes. This thread has a very good answer for this.
Question :
And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?
Answer :
Trust me. Try to write your own version to solve depth-first search iteratively. You will notice that some problems are easier to solve it recursively.
Hint : Recursion is good when you are solving a problem that can be solved by divide and conquer technique.
How to listen state changes in react.js?
I haven't used Angular, but reading the link above, it seems that you're trying to code for something that you don't need to handle. You make changes to state in your React component hierarchy (via this.setState()) and React will cause your component to be re-rendered (effectively 'listening' for changes).
If you want to 'listen' from another component in your hierarchy then you have two options:
- Pass handlers down (via props) from a common parent and have them update the parent's state, causing the hierarchy below the parent to be re-rendered.
- Alternatively, to avoid an explosion of handlers cascading down the hierarchy, you should look at the flux pattern, which moves your state into data stores and allows components to watch them for changes. The Fluxxor plugin is very useful for managing this.
When to use Comparable and Comparator
My need was sort based on date.
So, I used Comparable and it worked easily for me.
public int compareTo(GoogleCalendarBean o) {
// TODO Auto-generated method stub
return eventdate.compareTo(o.getEventdate());
}
One restriction with Comparable is that they cannot used for Collections other than List.
How to make lists contain only distinct element in Python?
Let me explain to you by an example:
if you have Python list
>>> randomList = ["a","f", "b", "c", "d", "a", "c", "e", "d", "f", "e"]
and you want to remove duplicates from it.
>>> uniqueList = []
>>> for letter in randomList:
if letter not in uniqueList:
uniqueList.append(letter)
>>> uniqueList
['a', 'f', 'b', 'c', 'd', 'e']
This is how you can remove duplicates from the list.
Under what circumstances can I call findViewById with an Options Menu / Action Bar item?
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab
I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
How to capture Curl output to a file?
For those of you want to copy the cURL output in the clipboard instead of outputting to a file, you can use pbcopy
by using the pipe |
after the cURL command.
Example: curl https://www.google.com/robots.txt | pbcopy
. This will copy all the content from the given URL to your clipboard.
Is Eclipse the best IDE for Java?
It is often said that there are better IDE's for various languages (eg Java) than Eclipse.
The power of Eclipse is that it's basically the same IDE for many languages, meaning that if you know you'll have to code in several programming languages (Java, C++, Python) it's a huge advantage that you only have to learn one IDE: Eclipse.
bash export command
Probably because it's trying to execute "export" as an external command, and it's a shell internal.
Print DIV content by JQuery
There is a way to use this with a hidden div but you have to work abit more with the printElement() function and css.
Css:
#SelectorToPrint{
display: none;
}
Script:
$("#SelectorToPrint").printElement({ printBodyOptions:{styleToAdd:'padding:10px;margin:10px;display:block', classNameToAdd:'WhatYouWant'}})
This will override the display: none in the new window you open and the content will be displayed on the print-preview page and the div on you site remains hidden.
How do I create a Linked List Data Structure in Java?
The obvious solution to developers familiar to Java is to use the LinkedList class already provided in java.util. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. Enhancements to this implementation include making it a double-linked list, adding methods to insert and delete from the middle or end, and by adding get and sort methods as well.
Note: In the example, the Link object doesn't actually contain another Link object - nextLink is actually only a reference to another link.
class Link {
public int data1;
public double data2;
public Link nextLink;
//Link constructor
public Link(int d1, double d2) {
data1 = d1;
data2 = d2;
}
//Print Link data
public void printLink() {
System.out.print("{" + data1 + ", " + data2 + "} ");
}
}
class LinkList {
private Link first;
//LinkList constructor
public LinkList() {
first = null;
}
//Returns true if list is empty
public boolean isEmpty() {
return first == null;
}
//Inserts a new Link at the first of the list
public void insert(int d1, double d2) {
Link link = new Link(d1, d2);
link.nextLink = first;
first = link;
}
//Deletes the link at the first of the list
public Link delete() {
Link temp = first;
if(first == null){
return null;
//throw new NoSuchElementException(); // this is the better way.
}
first = first.nextLink;
return temp;
}
//Prints list data
public void printList() {
Link currentLink = first;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
class LinkListTest {
public static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1, 1.01);
list.insert(2, 2.02);
list.insert(3, 3.03);
list.insert(4, 4.04);
list.insert(5, 5.05);
list.printList();
while(!list.isEmpty()) {
Link deletedLink = list.delete();
System.out.print("deleted: ");
deletedLink.printLink();
System.out.println("");
}
list.printList();
}
}
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Testing Private method using mockito
Put your test in the same package, but a different source folder (src/main/java vs. src/test/java) and make those methods package-private. Imo testability is more important than privacy.
Concatenate chars to form String in java
You can use StringBuilder:
StringBuilder sb = new StringBuilder();
sb.append('a');
sb.append('b');
sb.append('c');
String str = sb.toString()
Or if you already have the characters, you can pass a character array to the String constructor:
String str = new String(new char[]{'a', 'b', 'c'});
HTML input - name vs. id
name
identifies form fields* ; so they can be shared by controls that stand to represent multiple possibles values for such a field (radio buttons, checkboxes). They will be submitted as keys for form values.
id
identifies DOM elements ; so they can be targeted by CSS or Javascript.
* names also used to identify local anchors, but this is deprecated and 'id' is a preferred way to do so nowadays.
Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?
An IDE is an integrated development environment - a suped-up text editor with additional support for developing (such as forms designers, resource editors, etc), compiling and debugging applications. e.g Eclipse, Visual Studio.
A Library is a chunk of code that you can call from your own code, to help you do things more quickly/easily. For example, a Bitmap Processing library will provide facilities for loading and manipulating bitmap images, saving you having to write all that code for yourself. Typically a library will only offer one area of functionality (processing images or operating on zip files)
An API (application programming interface) is a term meaning the functions/methods in a library that you can call to ask it to do things for you - the interface to the library.
An SDK (software development kit) is a library or group of libraries (often with extra tool applications, data files and sample code) that aid you in developing code that uses a particular system (e.g. extension code for using features of an operating system (Windows SDK), drawing 3D graphics via a particular system (DirectX SDK), writing add-ins to extend other applications (Office SDK), or writing code to make a device like an Arduino or a mobile phone do what you want). An SDK will still usually have a single focus.
A toolkit is like an SDK - it's a group of tools (and often code libraries) that you can use to make it easier to access a device or system... Though perhaps with more focus on providing tools and applications than on just code libraries.
A framework is a big library or group of libraries that provides many services (rather than perhaps only one focussed ability as most libraries/SDKs do). For example, .NET provides an application framework - it makes it easier to use most (if not all) of the disparate services you need (e.g. Windows, graphics, printing, communications, etc) to write a vast range of applications - so one "library" provides support for pretty much everything you need to do. Often a framework supplies a complete base on which you build your own code, rather than you building an application that consumes library code to do parts of its work.
There are of course many examples in the wild that won't exactly match these descriptions though.
What's the default password of mariadb on fedora?
The default password is empty.
More accurately, you don't even NEED a password to login as root on the localhost. You just need to BE root.
But if you need to set the password the first time (if you allow remote access to root), you need to use:
sudo mysql_secure_installation
Enter empty password, then follow the instructions.
The problem you are having is that you need to BE root when you try to login as root from the local machine.
On Linux: mariadb will accept a connection as root on the socket (localhost) ONLY IF THE USER ASKING IT IS ROOT. Which means that even if you try
mysql -u root -p
And have the correct password you will be refused access. Same goes for
mysql_secure_installation
Mariadb will always refuse the password because the current user is not root. So you need to call them with sudo (or as the root user on your machine)
So locally you just want to use:
sudo mysql
and
sudo mysql_secure_installation
When moving from mysql to mariadb it took I will for me to figure this out.
How to convert string to IP address and vice versa
inet_ntoa()
converts a in_addr
to string:
The inet_ntoa function converts an
(Ipv4) Internet network address into
an ASCII string in Internet standard
dotted-decimal format.
inet_addr()
does the reverse job
The inet_addr function converts a
string containing an IPv4
dotted-decimal address into a proper
address for the IN_ADDR structure
PS this the first result googling "in_addr to string"!
PHP PDO with foreach and fetch
A PDOStatement
(which you have in $users
) is a forward-cursor. That means, once consumed (the first foreach
iteration), it won't rewind to the beginning of the resultset.
You can close the cursor after the foreach
and execute the statement again:
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
$users->execute();
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Or you could cache using tailored CachingIterator
with a fullcache:
$users = $dbh->query($sql);
$usersCached = new CachedPDOStatement($users);
foreach ($usersCached as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($usersCached as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
You find the CachedPDOStatement
class as a gist. The caching itertor is probably more sane than storing the resultset into an array because it still offers all properties and methods of the PDOStatement
object it has wrapped.
Convert List<Object> to String[] in Java
If we are very sure that List<Object>
will contain collection of String
, then probably try this.
List<Object> lst = new ArrayList<Object>();
lst.add("sample");
lst.add("simple");
String[] arr = lst.toArray(new String[] {});
System.out.println(Arrays.deepToString(arr));
Convert utf8-characters to iso-88591 and back in PHP
Have a look at iconv()
or mb_convert_encoding()
.
Just by the way: why don't utf8_encode()
and utf8_decode()
work for you?
utf8_decode — Converts a string with
ISO-8859-1 characters encoded with
UTF-8 to single-byte ISO-8859-1
utf8_encode — Encodes an ISO-8859-1
string to UTF-8
So essentially
$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded
$iso88591_1 = utf8_decode($utf8);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8);
$iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');
$iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded
$utf8_1 = utf8_encode($iso88591);
$utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591);
$utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');
all should do the same - with utf8_en/decode()
requiring no special extension, mb_convert_encoding()
requiring ext/mbstring and iconv()
requiring ext/iconv.
Search text in stored procedure in SQL Server
SELECT DISTINCT OBJECT_NAME([id]),[text]
FROM syscomments
WHERE [id] IN (SELECT [id] FROM sysobjects WHERE xtype IN
('TF','FN','V','P') AND status >= 0) AND
([text] LIKE '%text to be search%' )
OBJECT_NAME([id]) --> Object Name (View,Store Procedure,Scalar Function,Table function name)
id (int) = Object identification number
xtype char(2) Object type. Can be one of the following object types:
FN = Scalar function
P = Stored procedure
V = View
TF = Table function
javax.naming.NameNotFoundException
The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.
As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:
/com/mypackage/MyEJB.class
/com/mypackage/MyEJBInterface.class
/com/mypackage/etc... etc... java classes
/META-INF/ejb-jar.xml
/META-INF/jboss.xml
The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.
BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is
@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
public void bussinesMethod(){
}
}
No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.
Now in your client code you need to lookup "MyComponentName".
When should I use UNSIGNED and SIGNED INT in MySQL?
I think, UNSIGNED
would be the best option to store something like time_duration
(Eg: resolved_call_time = resolved_time(DateTime)-creation_time(DateTime)
) value in minutes or hours or seconds format which will definitely be a non-negative number
Convert String To date in PHP
Simple exploding should do the trick:
$monthNamesToInt = array('Jan'=>1,'Feb'=>2, 'Mar'=>3 /*, [...]*/ );
$datetime = '05/Feb/2010:14:00:01';
list($date,$hour,$minute,$second) = explode(':',$datetime);
list($day,$month,$year) = explode('/',$date);
$unixtime = mktime((int)$hour, (int)$minute, (int)$second, $monthNamesToInt[$month], (int)$day, (int)$year);
Installing Bootstrap 3 on Rails App
For me, the simplest way to do this is
1) Download and unzip bootstrap into vendor
2) Add the bootstrap path to your config
config.assets.paths << Rails.root.join("vendor/bootstrap-3.3.6-dist")
3) Require them
in css *= require css/bootstrap
in js //= require js/bootstrap
Done!
This methods makes the fonts load without any other special configuration and doesn't require moving the bootstrap files out of their self-contained directory.
Convert time in HH:MM:SS format to seconds only?
Simple
function timeToSeconds($time)
{
$timeExploded = explode(':', $time);
if (isset($timeExploded[2])) {
return $timeExploded[0] * 3600 + $timeExploded[1] * 60 + $timeExploded[2];
}
return $timeExploded[0] * 3600 + $timeExploded[1] * 60;
}
How to style a select tag's option element?
Since version 49+, Chrome has supported styling <option>
elements with font-weight
. Source: https://code.google.com/p/chromium/issues/detail?id=44917#c22
New SELECT Popup: font-weight style should be applied.
This CL removes themeChromiumSkia.css. |!important|
in it prevented to
apply font-weight
. Now html.css has |font-weight:normal|
, and
|!important|
should be unnecessary.
There was a Chrome stylesheet, themeChromiumSkia.css, that used font-weight: normal !important;
in it all this time. It was introduced to the stable Chrome channel in version 49.0.
Python list iterator behavior and next(iterator)
I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.
Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.
In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.
(One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)
The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...
bash: npm: command not found?
I know it's an old question. But it keeps showing in google first position and all it says it's "install node.js".
For a newbie this is not obvious, so all you have to do is go to the node.js website and search for the command for your linux distribution version or any other operating system. Here is the link:
https://nodejs.org/en/download/package-manager/
In this page you have to choose your operating system and you'll find your command. Then you just log into your console as a root (using putty for instance) and execute that command.
After that, you log as normal user and go again inside your laravel application folder and run again npm install command, and it should work.
Hope it helps.
Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
I found another solution to get the data. according to the documentation Please check documentation link
In service file add following.
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable()
export class MoviesService {
constructor(private db: AngularFireDatabase) {}
getMovies() {
this.db.list('/movies').valueChanges();
}
}
In Component add following.
import { Component, OnInit } from '@angular/core';
import { MoviesService } from './movies.service';
@Component({
selector: 'app-movies',
templateUrl: './movies.component.html',
styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
movies$;
constructor(private moviesDb: MoviesService) {
this.movies$ = moviesDb.getMovies();
}
In your html file add following.
<li *ngFor="let m of movies$ | async">{{ m.name }} </li>
importing pyspark in python shell
On Mac, I use Homebrew to install Spark (formula "apache-spark"). Then, I set the PYTHONPATH this way so the Python import works:
export SPARK_HOME=/usr/local/Cellar/apache-spark/1.2.0
export PYTHONPATH=$SPARK_HOME/libexec/python:$SPARK_HOME/libexec/python/build:$PYTHONPATH
Replace the "1.2.0" with the actual apache-spark version on your mac.
What is the best JavaScript code to create an img element
This is the method I follow to create a loop of img tags or a single tag as ur wish
method1 :
let pics=document.getElementById("pics-thumbs");
let divholder=document.createDocumentFragment();
for(let i=1;i<73;i++)
{
let img=document.createElement("img");
img.class="img-responsive";
img.src=`images/fun${i}.jpg`;
divholder.appendChild(img);
}
pics.appendChild(divholder);
or
method2:
let pics = document.getElementById("pics-thumbs"),
imgArr = [];
for (let i = 1; i < 73; i++) {
imgArr.push(`<img class="img-responsive" src="images/fun${i}.jpg">`);
}
pics.innerHTML = imgArr.join('<br>')
<div id="pics-thumbs"></div>
jQuery - Fancybox: But I don't want scrollbars!
Remove the quotes around your height and width values:
<script type="text/javascript">
$(document).ready(function() {
$("a#regForm").fancybox({
'titleShow' : false,
'autoscale' : true,
'width' : 450,
'height' : 700,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic'
});
});
</script>
jQuery Dialog Box
Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well:
$(document).ready({
$('a.TOClink').click(function(){
showTOC();
});
});
function showTOC() {
$('#example').dialog({modal:true});
}
A more concise example which accomplishes the desired effect using the jQuery UI dialog is:
<div id="terms" style="display:none;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<a id="showTerms" href="#">Show Terms & Conditions</a>
<script type="text/javascript">
$(document).ready(function(){
$('#showTerms').click(function(){
$('#terms').dialog({modal:true});
});
});
</script>
SQL to LINQ Tool
I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).
When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.
It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.
Java ArrayList how to add elements at the beginning
import java.util.*:
public class Logic {
List<String> list = new ArrayList<String>();
public static void main(String...args) {
Scanner input = new Scanner(System.in);
Logic obj = new Logic();
for (int i=0;i<=20;i++) {
String string = input.nextLine();
obj.myLogic(string);
obj.printList();
}
}
public void myLogic(String strObj) {
if (this.list.size()>=10) {
this.list.remove(this.list.size()-1);
} else {
list.add(strObj);
}
}
public void printList() {
System.out.print(this.list);
}
}
What does 'low in coupling and high in cohesion' mean
Do you have a smart phone? Is there one big app or lots of little ones? Does one app reply upon another? Can you use one app while installing, updating, and/or uninstalling another? That each app is self-contained is high cohesion. That each app is independent of the others is low coupling. DevOps favours this architecture because it means you can do discrete continuous deployment without disrupting the system entire.
Replace non ASCII character from string
You can try something like this. Special Characters range for alphabets starts from 192, so you can avoid such characters in the result.
String name = "A função";
StringBuilder result = new StringBuilder();
for(char val : name.toCharArray()) {
if(val < 192) result.append(val);
}
System.out.println("Result "+result.toString());
How can I pass parameters to a partial view in mvc 4
Your question is hard to understand, but if I'm getting the gist, you simply have some value in your main view that you want to access in a partial being rendered in that view.
If you just render a partial with just the partial name:
@Html.Partial("_SomePartial")
It will actually pass your model as an implicit parameter, the same as if you were to call:
@Html.Partial("_SomePartial", Model)
Now, in order for your partial to actually be able to use this, though, it too needs to have a defined model, for example:
@model Namespace.To.Your.Model
@Html.Action("MemberProfile", "Member", new { id = Model.Id })
Alternatively, if you're dealing with a value that's not on your view's model (it's in the ViewBag or a value generated in the view itself somehow, then you can pass a ViewDataDictionary
@Html.Partial("_SomePartial", new ViewDataDictionary { { "id", someInteger } });
And then:
@Html.Action("MemberProfile", "Member", new { id = ViewData["id"] })
As with the model, Razor will implicitly pass your partial the view's ViewData
by default, so if you had ViewBag.Id
in your view, then you can reference the same thing in your partial.
XSS filtering function in PHP
There are a number of ways hackers put to use for XSS attacks, PHP's built-in functions do not respond to all sorts of XSS attacks. Hence, functions such as strip_tags, filter_var, mysql_real_escape_string, htmlentities, htmlspecialchars, etc do not protect us 100%. You need a better mechanism, here is what is solution:
function xss_clean($data)
{
// Fix &entity\n;
$data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
// Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
// Remove namespaced elements (we do not need them)
$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);
do
{
// Remove really unwanted tags
$old_data = $data;
$data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
}
while ($old_data !== $data);
// we are done...
return $data;
}
Base64: java.lang.IllegalArgumentException: Illegal character
The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.
For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.
static String getBase64EncodedCipherText(String cipherText) {
byte[] cText = cipherText.getBytes();
// return an ISO-8859-1 encoded String
return Base64.getEncoder().encodeToString(cText);
}
static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
return new String((Base64.getDecoder().decode(encodedCipherText)));
}
public static void main(String[] args) {
try {
String cText = getRawCipherText(null, "Hello World of Encryption...");
System.out.println("Text to encrypt/encode: Hello World of Encryption...");
// This output is a simple sanity check to display that the text
// has indeed been converted to a cipher text which
// is unreadable by all but the most intelligent of programmers.
// It is absolutely inhuman of me to do such a thing, but I am a
// rebel and cannot be trusted in any way. Please look away.
System.out.println("RAW CIPHER TEXT: " + cText);
cText = getBase64EncodedCipherText(cText);
System.out.println("BASE64 ENCODED: " + cText);
// There he goes again!!
System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText));
System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
} catch (Exception e) {
e.printStackTrace();
}
}
The output looks like:
Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED: q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...
Field 'id' doesn't have a default value?
I had an issue on AWS with mariadb - This is how I solved the STRICT_TRANS_TABLES issue
SSH into server and chanege to the ect directory
[ec2-user]$ cd /etc
Make a back up of my.cnf
[ec2-user etc]$ sudo cp -a my.cnf{,.strict.bak}
I use nano to edit but there are others
[ec2-user etc]$ sudo nano my.cnf
Add this line in the the my.cnf file
#
#This removes STRICT_TRANS_TABLES
#
sql_mode=""
Then exit and save
OR if sql_mode is there something like this:
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
Change to
sql_mode=""
exit and save
then restart the database
[ec2-user etc]$ sudo systemctl restart mariadb
How to Convert Boolean to String
I'm not a fan of the accepted answer as it converts anything which evaluates to false to "false"
no just boolean and vis-versa.
Anyway here's my O.T.T answer, it uses the var_export
function.
var_export
works with all variable types except resource
, I have created a function which will perform a regular cast to string ((string)
), a strict cast (var_export
) and a type check, depending on the arguments provided..
if(!function_exists('to_string')){
function to_string($var, $strict = false, $expectedtype = null){
if(!func_num_args()){
return trigger_error(__FUNCTION__ . '() expects at least 1 parameter, 0 given', E_USER_WARNING);
}
if($expectedtype !== null && gettype($var) !== $expectedtype){
return trigger_error(__FUNCTION__ . '() expects parameter 1 to be ' . $expectedtype .', ' . gettype($var) . ' given', E_USER_WARNING);
}
if(is_string($var)){
return $var;
}
if($strict && !is_resource($var)){
return var_export($var, true);
}
return (string) $var;
}
}
if(!function_exists('bool_to_string')){
function bool_to_string($var){
return func_num_args() ? to_string($var, true, 'boolean') : to_string();
}
}
if(!function_exists('object_to_string')){
function object_to_string($var){
return func_num_args() ? to_string($var, true, 'object') : to_string();
}
}
if(!function_exists('array_to_string')){
function array_to_string($var){
return func_num_args() ? to_string($var, true, 'array') : to_string();
}
}
Why would one omit the close tag?
According to the docs, it's preferable to omit the closing tag if it's at the end of the file for the following reason:
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
PHP Manual > Language Reference > Basic syntax > PHP tags
Passing arrays as parameters in bash
Requirement: Function to find a string in an array.
This is a slight simplification of DevSolar's solution in that it uses the arguments passed rather than copying them.
myarray=('foobar' 'foxbat')
function isInArray() {
local item=$1
shift
for one in $@; do
if [ $one = $item ]; then
return 0 # found
fi
done
return 1 # not found
}
var='foobar'
if isInArray $var ${myarray[@]}; then
echo "$var found in array"
else
echo "$var not found in array"
fi
How to create an array for JSON using PHP?
Use PHP's native json_encode
, like this:
<?php
$arr = array(
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
)
);
echo json_encode($arr);
?>
Update: To answer your question in the comment. You do it like this:
$named_array = array(
"nome_array" => array(
array(
"foo" => "bar"
),
array(
"foo" => "baz"
)
)
);
echo json_encode($named_array);
SQL select statements with multiple tables
First select all record from person table, then join all these record with another table 'Address'...now u have record of all the persons who have their address in address table...so finally filter your record by zipcode.
select * from Person as P inner join Address as A on
P.id = A.person_id Where A.zip='97229'
PHP: How to use array_filter() to filter array keys?
How to get the current key of an array when using array_filter
Regardless of how I like Vincent's solution for Macek's problem, it doesn't actually use array_filter
. If you came here from a search engine you maybe where looking for something like this (PHP >= 5.3):
$array = ['apple' => 'red', 'pear' => 'green'];
reset($array); // Unimportant here, but make sure your array is reset
$apples = array_filter($array, function($color) use ($&array) {
$key = key($array);
next($array); // advance array pointer
return key($array) === 'apple';
}
It passes the array you're filtering as a reference to the callback. As array_filter
doesn't conventionally iterate over the array by increasing it's public internal pointer you have to advance it by yourself.
What's important here is that you need to make sure your array is reset, otherwise you might start right in the middle of it.
In PHP >= 5.4 you could make the callback even shorter:
$apples = array_filter($array, function($color) use ($&array) {
return each($array)['key'] === 'apple';
}
When restoring a backup, how do I disconnect all active connections?
To add to advice already given, if you have a web app running through IIS that uses the DB, you may also need to stop (not recycle) the app pool for the app while you restore, then re-start. Stopping the app pool kills off active http connections and doesn't allow any more, which could otherwise end up allowing processes to be triggered that connect to and thereby lock the database. This is a known issue for example with the Umbraco Content Management System when restoring its database
What is the difference between __dirname and ./ in node.js?
./
refers to the current working directory, except in the require()
function. When using require()
, it translates ./
to the directory of the current file called. __dirname
is always the directory of the current file.
For example, with the following file structure
/home/user/dir/files/config.json
{
"hello": "world"
}
/home/user/dir/files/somefile.txt
text file
/home/user/dir/dir.js
var fs = require('fs');
console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));
If I cd
into /home/user/dir
and run node dir.js
I will get
{ hello: 'world' }
text file
But when I run the same script from /home/user/
I get
{ hello: 'world' }
Error: ENOENT, no such file or directory './files/somefile.txt'
at Object.openSync (fs.js:228:18)
at Object.readFileSync (fs.js:119:15)
at Object.<anonymous> (/home/user/dir/dir.js:4:16)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
Using ./
worked with require
but not for fs.readFileSync
. That's because for fs.readFileSync
, ./
translates into the cwd (in this case /home/user/
). And /home/user/files/somefile.txt
does not exist.
Creating a recursive method for Palindrome
Here is the code for palindrome check without creating many strings
public static boolean isPalindrome(String str){
return isPalindrome(str,0,str.length()-1);
}
public static boolean isPalindrome(String str, int start, int end){
if(start >= end)
return true;
else
return (str.charAt(start) == str.charAt(end)) && isPalindrome(str, start+1, end-1);
}
Switch statement: must default be the last case?
The default
condition can be anyplace within the switch that a case clause can exist. It is not required to be the last clause. I have seen code that put the default as the first clause. The case 2:
gets executed normally, even though the default clause is above it.
As a test, I put the sample code in a function, called test(int value){}
and ran:
printf("0=%d\n", test(0));
printf("1=%d\n", test(1));
printf("2=%d\n", test(2));
printf("3=%d\n", test(3));
printf("4=%d\n", test(4));
The output is:
0=2
1=1
2=4
3=8
4=10
How to show live preview in a small popup of linked page on mouse over on link?
HTML structure
<div id="app">
<div class="box">
<div class="title">How to preview link with iframe and javascript?</div>
<div class="note"><small>Note: Click to every link on content below to preview</small></div>
<div id="content">
We'll first attach all the events to all the links for which we want to <a href="https://htmlcssdownload.com/">preview</a> with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.
</div>
<h3>Preview the link</h3>
<div id="result"></div>
</div>
We'll first attach all the events to all the links for which we want to preview with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.
<script type="text/javascript">
(()=>{
let content = document.getElementById('content');
let links = content.getElementsByTagName('a');
for (let index = 0; index < links.length; index++) {
const element = links[index];
element.addEventListener('click',(e)=>{
e.preventDefault();
openDemoLink(e.target.href);
})
}
function openDemoLink(link){
let div = document.createElement('div');
div.classList.add('preview_frame');
let frame = document.createElement('iframe');
frame.src = link;
let close = document.createElement('a');
close.classList.add('close-btn');
close.innerHTML = "Click here to close the example";
close.addEventListener('click', function(e){
div.remove();
})
div.appendChild(frame);
div.appendChild(close);
document.getElementById('result').appendChild(div);
}
})()
To see detail at How to live preview link
how to generate web service out of wsdl
How about using the wsdl /server
or wsdl /serverinterface
switches?
As far as I understand the wsdl.exe command line properties, that's what you're looking for.
- ADVANCED -
/server
Server switch has been deprecated. Please use /serverInterface instead.
Generate an abstract class for an xml web service implementation using
ASP.NET based on the contracts. The default is to generate client proxy
classes.
On the other hand: why do you want to create obsolete technology solutions? Why not create this web service as a WCF service. That's the current and more modern, much more flexible way to do this!
Marc
UPDATE:
When I use wsdl /server
on a WSDL file, I get this file created:
[WebService(Namespace="http://.......")]
public abstract partial class OneCrmServiceType : System.Web.Services.WebService
{
/// <remarks/>
[WebMethod]
public abstract void OrderCreated(......);
}
This is basically almost exactly the same code that gets generated when you add an ASMX file to your solution (in the code behind file - "yourservice.asmx.cs"). I don't think you can get any closer to creating an ASMX file from a WSDL file.
You can always add the "yourservice.asmx" manually - it doesn't really contain much:
<%@ WebService Language="C#" CodeBehind="YourService.asmx.cs"
Class="YourServiceNamespace.YourServiceClass" %>
How to unzip files programmatically in Android?
According to @zapl answer,Unzip with progress report:
public interface UnzipFile_Progress
{
void Progress(int percent, String FileName);
}
// unzip(new File("/sdcard/pictures.zip"), new File("/sdcard"));
public static void UnzipFile(File zipFile, File targetDirectory, UnzipFile_Progress progress) throws IOException,
FileNotFoundException
{
long total_len = zipFile.length();
long total_installed_len = 0;
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
try
{
ZipEntry ze;
int count;
byte[] buffer = new byte[1024];
while ((ze = zis.getNextEntry()) != null)
{
if (progress != null)
{
total_installed_len += ze.getCompressedSize();
String file_name = ze.getName();
int percent = (int)(total_installed_len * 100 / total_len);
progress.Progress(percent, file_name);
}
File file = new File(targetDirectory, ze.getName());
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Failed to ensure directory: " + dir.getAbsolutePath());
if (ze.isDirectory())
continue;
FileOutputStream fout = new FileOutputStream(file);
try
{
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally
{
fout.close();
}
// if time should be restored as well
long time = ze.getTime();
if (time > 0)
file.setLastModified(time);
}
} finally
{
zis.close();
}
}
Can a CSV file have a comment?
The CSV "standard" (such as it is) does not dictate how comments should be handled, no, it's up to the application to establish a convention and stick with it.
Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?
warning: LF will be replaced by CRLF.
Depending on the editor you are using, a text file with LF wouldn't necessary be saved with CRLF: recent editors can preserve eol style. But that git config setting insists on changing those...
Simply make sure that (as I recommend here):
git config --global core.autocrlf false
That way, you avoid any automatic transformation, and can still specify them through a .gitattributes
file and core.eol
directives.
windows git "LF will be replaced by CRLF"
Is this warning tail backward?
No: you are on Windows, and the git config
help page does mention
Use this setting if you want to have CRLF
line endings in your working directory even though the repository does not have normalized line endings.
As described in "git replacing LF with CRLF", it should only occur on checkout (not commit), with core.autocrlf=true
.
repo
/ \
crlf->lf lf->crlf
/ \
As mentioned in XiaoPeng's answer, that warning is the same as:
warning: (If you check it out/or clone to another folder with your current core.autocrlf
configuration,) LF will be replaced by CRLF
The file will have its original line endings in your (current) working directory.
As mentioned in git-for-windows/git
issue 1242:
I still feel this message is confusing, the message could be extended to include a better explanation of the issue, for example: "LF will be replaced by CRLF in file.json
after removing the file and checking it out again".
Note: Git 2.19 (Sept 2018), when using core.autocrlf
, the bogus "LF
will be replaced by CRLF" warning is now suppressed.
As quaylar rightly comments, if there is a conversion on commit, it is to LF
only.
That specific warning "LF will be replaced by CRLF
" comes from convert.c#check_safe_crlf():
if (checksafe == SAFE_CRLF_WARN)
warning("LF will be replaced by CRLF in %s.
The file will have its original line endings
in your working directory.", path);
else /* i.e. SAFE_CRLF_FAIL */
die("LF would be replaced by CRLF in %s", path);
It is called by convert.c#crlf_to_git()
, itself called by convert.c#convert_to_git()
, itself called by convert.c#renormalize_buffer()
.
And that last renormalize_buffer()
is only called by merge-recursive.c#blob_unchanged()
.
So I suspect this conversion happens on a git commit
only if said commit is part of a merge process.
Note: with Git 2.17 (Q2 2018), a code cleanup adds some explanation.
See commit 8462ff4 (13 Jan 2018) by Torsten Bögershausen (tboegi
).
(Merged by Junio C Hamano -- gitster
-- in commit 9bc89b1, 13 Feb 2018)
convert_to_git(): safe_crlf/checksafe becomes int conv_flags
When calling convert_to_git()
, the checksafe
parameter defined what
should happen if the EOL conversion (CRLF --> LF --> CRLF
) does not
roundtrip cleanly.
In addition, it also defined if line endings should be renormalized (CRLF --> LF
) or kept as they are.
checksafe was an safe_crlf
enum with these values:
SAFE_CRLF_FALSE: do nothing in case of EOL roundtrip errors
SAFE_CRLF_FAIL: die in case of EOL roundtrip errors
SAFE_CRLF_WARN: print a warning in case of EOL roundtrip errors
SAFE_CRLF_RENORMALIZE: change CRLF to LF
SAFE_CRLF_KEEP_CRLF: keep all line endings as they are
Note that a regression introduced in 8462ff4 ("convert_to_git()
:
safe_crlf/checksafe
becomes int conv_flags
", 2018-01-13, Git 2.17.0) back in Git 2.17 cycle caused autocrlf
rewrites to produce a warning message
despite setting safecrlf=false
.
See commit 6cb0912 (04 Jun 2018) by Anthony Sottile (asottile
).
(Merged by Junio C Hamano -- gitster
-- in commit 8063ff9, 28 Jun 2018)
How do I fix a NoSuchMethodError?
The problem in my case was having two versions of the same library in the build path. The older version of the library didn't have the function, and newer one did.
How to sort in mongoose?
Chaining with the query builder interface in Mongoose 4.
// Build up a query using chaining syntax. Since no callback is passed this will create an instance of Query.
var query = Person.
find({ occupation: /host/ }).
where('name.last').equals('Ghost'). // find each Person with a last name matching 'Ghost'
where('age').gt(17).lt(66).
where('likes').in(['vaporizing', 'talking']).
limit(10).
sort('-occupation'). // sort by occupation in decreasing order
select('name occupation'); // selecting the `name` and `occupation` fields
// Excute the query at a later time.
query.exec(function (err, person) {
if (err) return handleError(err);
console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host
})
See the docs for more about queries.
How can I revert a single file to a previous version?
Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.
Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.
I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5
, copy the file somewhere else, checkout master
, copy the file back, then commit.
How do I use variables in Oracle SQL Developer?
You can read up elsewhere on substitution variables; they're quite handy in SQL Developer. But I have fits trying to use bind variables in SQL Developer. This is what I do:
SET SERVEROUTPUT ON
declare
v_testnum number;
v_teststring varchar2(1000);
begin
v_testnum := 2;
DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);
SELECT 36,'hello world'
INTO v_testnum, v_teststring
from dual;
DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);
DBMS_OUTPUT.put_line('v_teststring is ' || v_teststring);
end;
SET SERVEROUTPUT ON
makes it so text can be printed to the script output console.
I believe what we're doing here is officially called PL/SQL. We have left the pure SQL land and are using a different engine in Oracle. You see the SELECT
above? In PL/SQL you always have to SELECT ... INTO
either variable or a refcursor. You can't just SELECT
and return a result set in PL/SQL.
compilation error: identifier expected
You must to wrap your following code into a block (Either method or static).
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
Without a block you can only declare variables and more than that assign them a value in single statement.
For method main() will be best choice for now:
public class details {
public static void main(String[] args){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
or If you want to use static block then...
public class details {
static {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
or if you want to build another method then..
public class details {
public static void main(String[] args){
myMethod();
}
private static void myMethod(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
Also worry about exception due to BufferedReader .
How to return a value from try, catch, and finally?
It is because you are in a try
statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally
block, that way it will for sure be returned.
Make sure that you initialize sum outside the try/catch/finally
so that it is in scope.
Convert array of strings into a string in Java
Try the Arrays.toString overloaded methods.
Or else, try this below generic implementation:
public static void main(String... args) throws Exception {
String[] array = {"ABC", "XYZ", "PQR"};
System.out.println(new Test().join(array, ", "));
}
public <T> String join(T[] array, String cement) {
StringBuilder builder = new StringBuilder();
if(array == null || array.length == 0) {
return null;
}
for (T t : array) {
builder.append(t).append(cement);
}
builder.delete(builder.length() - cement.length(), builder.length());
return builder.toString();
}
check null,empty or undefined angularjs
just use -
if(!a) // if a is negative,undefined,null,empty value then...
{
// do whatever
}
else {
// do whatever
}
this works because of the == difference from === in javascript, which converts some values to "equal" values in other types to check for equality, as opposed for === which simply checks if the values equal. so basically the == operator know to convert the "", null, undefined to a false value. which is exactly what you need.
Better way to find control in ASP.NET
If you're looking for a specific type of control you could use a recursive loop like this one -
http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx
Here's an example I made that returns all controls of the given type
/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control
{
private readonly List<T> _foundControls = new List<T>();
public IEnumerable<T> FoundControls
{
get { return _foundControls; }
}
public void FindChildControlsRecursive(Control control)
{
foreach (Control childControl in control.Controls)
{
if (childControl.GetType() == typeof(T))
{
_foundControls.Add((T)childControl);
}
else
{
FindChildControlsRecursive(childControl);
}
}
}
}
Loop through all nested dictionary values?
These answers work for only 2 levels of sub-dictionaries. For more try this:
nested_dict = {'dictA': {'key_1': 'value_1', 'key_1A': 'value_1A','key_1Asub1': {'Asub1': 'Asub1_val', 'sub_subA1': {'sub_subA1_key':'sub_subA1_val'}}},
'dictB': {'key_2': 'value_2'},
1: {'key_3': 'value_3', 'key_3A': 'value_3A'}}
def print_dict(dictionary):
dictionary_array = [dictionary]
for sub_dictionary in dictionary_array:
if type(sub_dictionary) is dict:
for key, value in sub_dictionary.items():
print("key=", key)
print("value", value)
if type(value) is dict:
dictionary_array.append(value)
print_dict(nested_dict)
Unable to Install Any Package in Visual Studio 2015
I am using Visual Studio 2015 Update 3 and I managed to reproduce this error (despite Update 3 allegedly containing a fix).
As suggested above, a reliable fix is to do the following... 1) Exit Visual Studio, 2) Delete the packages folder, 3) Restart VS.
But... if you don't want to immediately exit VS for some reason, I was still able to add/remove packages from all projects by choosing the 'Manage NuGet Packages for Solution' option, rather than the individual Project with the issue.
How to decompile a whole Jar file?
First of all, it's worth remembering that all Java archive files (.jar
/.war
/etc...) are all basically just fancy.zip
files, with a few added manifests and metadata.
Second, to tackle this problem I personally use several tools which handle this problem on all levels:
- Jad + Jadclipse while working in IDE for decompiling
.class
files
- WinRAR, my favorite compression tool natively supports Java archives (again, see first paragraph).
- Beyond Compare, my favorite diff tool, when configured correctly can do on-the-fly comparisons between any archive file, including
jar
s. Well worth a try.
The advantage of all the aforementioned, is that I do not need to hold any other external tool which clutters my work environment. Everything I will ever need from one of those files can be handled inside my IDE or diffed with other files natively.
C++ - Hold the console window open?
How about std::cin.get();
?
Also, if you're using Visual Studio, you can run without debugging (CTRL-F5 by default) and it won't close the console at the end. If you run it with debugging, you could always put a breakpoint at the closing brace of main()
.
How can I hide/show a div when a button is clicked?
This works:
_x000D_
_x000D_
function showhide(id) {_x000D_
var e = document.getElementById(id);_x000D_
e.style.display = (e.style.display == 'block') ? 'none' : 'block';_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html> _x000D_
<body>_x000D_
_x000D_
<a href="javascript:showhide('uniquename')">_x000D_
Click to show/hide._x000D_
</a>_x000D_
_x000D_
<div id="uniquename" style="display:none;">_x000D_
<p>Content goes here.</p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
spark submit add multiple jars in classpath
Pass --jars
with the path of jar
files separated by ,
to spark-submit
.
For reference:
--driver-class-path is used to mention "extra" jars to add to the "driver" of the spark job
--driver-library-path is used to "change" the default library path for the jars needed for the spark driver
--driver-class-path will only push the jars to the driver machine. If you want to send the jars to "executors", you need to use --jars
And to set the jars programatically set the following config:
spark.yarn.dist.jars
with comma-separated list of jars.
Eg:
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Spark config example") \
.config("spark.yarn.dist.jars", "<path-to-jar/test1.jar>,<path-to-jar/test2.jar>") \
.getOrCreate()
Embed an External Page Without an Iframe?
Why not use PHP! It's all server side:
<?php print file_get_contents("http://foo.com")?>
If you own both sites, you may need to ok this transaction with full declaration of headers at the server end. Works beautifully.
Why don't self-closing script elements work?
Internet Explorer 8 and earlier do not support XHTML parsing. Even if you use an XML declaration and/or an XHTML doctype, old IE still parse the document as plain HTML. And in plain HTML, the self-closing syntax is not supported. The trailing slash is just ignored, you have to use an explicit closing tag.
Even browsers with support for XHTML parsing, such as IE 9 and later, will still parse the document as HTML unless you serve the document with a XML content type. But in that case old IE will not display the document at all!
memcpy() vs memmove()
I have tried to run same program using eclipse and it shows clear difference between memcpy
and memmove
. memcpy()
doesn't care about overlapping of memory location which results in corruption of data, while memmove()
will copy data to temporary variable first and then copy into actual memory location.
While trying to copy data from location str1
to str1+2
, output of memcpy
is "aaaaaa
". The question would be how?
memcpy()
will copy one byte at a time from left to right. As shown in your program "aabbcc
" then
all copying will take place as below,
aabbcc -> aaabcc
aaabcc -> aaaacc
aaaacc -> aaaaac
aaaaac -> aaaaaa
memmove()
will copy data to temporary variable first and then copy to actual memory location.
aabbcc(actual) -> aabbcc(temp)
aabbcc(temp) -> aaabcc(act)
aabbcc(temp) -> aaaacc(act)
aabbcc(temp) -> aaaabc(act)
aabbcc(temp) -> aaaabb(act)
Output is
memcpy
: aaaaaa
memmove
: aaaabb
JPA 2.0, Criteria API, Subqueries, In Expressions
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Employee> criteriaQuery = criteriaBuilder.createQuery(Employee.class);
Root<Employee> empleoyeeRoot = criteriaQuery.from(Employee.class);
Subquery<Project> projectSubquery = criteriaQuery.subquery(Project.class);
Root<Project> projectRoot = projectSubquery.from(Project.class);
projectSubquery.select(projectRoot);
Expression<String> stringExpression = empleoyeeRoot.get(Employee_.ID);
Predicate predicateIn = stringExpression.in(projectSubquery);
criteriaQuery.select(criteriaBuilder.count(empleoyeeRoot)).where(predicateIn);
How to remove part of a string?
string = "removeTHISplease";
result = string.replace('THIS','');
I think replace do the same thing like a some own function. For me this works.
nano error: Error opening terminal: xterm-256color
Mine was quite a unique case but this could help someone. On Android I tried to copy nano from my termux binary folder to /system/xbin. Placed all the library dependencies in /system/lib and got this error. The libncurses.so.6 file I copied from termux had it's TERMINFO file still pointed to /data/data/com.termux/files/usr/share/terminfo
View pointed path with command
strings path-to-libncurses.so | grep /terminfo
To fix either make the termux terminfo dir and subdirs readable and executable by the nano user or copy the terminfo folder somewhere else and use a hexeditor to modify the plain text path in the shared library file.
Link to zipped terminfo folder
https://drive.google.com/file/d/1m1tfHgkGRehBGh1jPMK4EaTgQb9EyCG7/view?usp=drivesdk
How to keep a git branch in sync with master
You are thinking in the right direction. Merge master with mobiledevicesupport continuously and merge mobiledevicesupport with master when mobiledevicesupport is stable. Each developer will have his own branch and can merge to and from either on master or mobiledevicesupport depending on their role.
CSS : center form in page horizontally and vertically
if you use a negative translateX/Y
width and height are not necessary and the style is really short
_x000D_
_x000D_
#form_login {
left : 50%;
top : 50%;
position : absolute;
transform : translate(-50%, -50%);
}
_x000D_
<form id="form_login">
<p>
<input type="text" id="username" placeholder="username" />
</p>
<p>
<input type="password" id="password" placeholder="password" />
</p>
<p>
<input type="text" id="server" placeholder="server" />
</p>
<p>
<button id="submitbutton" type="button">Se connecter</button>
</p>
</form>
_x000D_
_x000D_
_x000D_
Alternatively you could use display: grid
(check the full page view)
_x000D_
_x000D_
body {
margin : 0;
padding : 0;
display : grid;
place-content : center;
min-height : 100vh;
}
_x000D_
<form id="form_login">
<p>
<input type="text" id="username" placeholder="username" />
</p>
<p>
<input type="password" id="password" placeholder="password" />
</p>
<p>
<input type="text" id="server" placeholder="server" />
</p>
<p>
<button id="submitbutton" type="button">Se connecter</button>
</p>
</form>
_x000D_
_x000D_
_x000D_
How to disable action bar permanently
Use this in styles.xml
file:
<style name="MyTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
C++ Redefinition Header Files (winsock2.h)
I checked the recursive includes, I spotted the header files which include (recursively) some #include "windows.h"
and #include "Winsock.h"
and write a #include "Winsock2.h"
. in this files, i added #include "Winsock2.h"
as the first include.
Just a matter of patience, look at includes one by one and establish this order, first #include "Winsock2.h"
then #include "windows.h"
How to get the current directory of the cmdlet being executed
Path is often null. This function is safer.
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value;
if($Invocation.PSScriptRoot)
{
$Invocation.PSScriptRoot;
}
Elseif($Invocation.MyCommand.Path)
{
Split-Path $Invocation.MyCommand.Path
}
else
{
$Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
}
}
Java check if boolean is null
boolean is a primitive data type in Java and primitive data types can not be null like other primitives int, float etc, they should be containing default values if not assigned.
In Java, only objects can assigned to null, it means the corresponding object has no reference and so does not contain any representation in memory.
Hence If you want to work with object as null , you should be using Boolean class which wraps a primitive boolean type value inside its object.
These are called wrapper classes in Java
For Example:
Boolean bool = readValue(...); // Read Your Value
if (bool == null) { do This ...}
Android: Reverse geocoding - getFromLocation
The following code snippet is doing it for me (lat and lng are doubles declared above this bit):
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
How to set time to a date object in java
Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")
CSS image overlay with color and transparency
If you want to make the reverse of what you showed consider doing this:
.tint:hover:before {
background: rgba(0,0,250, 0.5);
}
.t2:before {
background: none;
}
and look at the effect on the 2nd picture.
Is it supposed to look like this?
Bash Script : what does #!/bin/bash mean?
When the first characters in a script are #!
, that is called the shebang. If your file starts with
#!/path/to/something
the standard is to run something
and pass the rest of the file to that program as an input.
With that said, the difference between #!/bin/bash
, #!/bin/sh
, or even #!/bin/zsh
is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash
and sh
are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh
is a link to dash
, and on traditional Unix systems (Solaris, Irix, etc) bash
is usually a completely different program from sh
.
Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python
, #!/usr/bin/perl
, or even #!/usr/local/bin/my_own_scripting_language
.
Disable/enable an input with jQuery?
You can use the jQuery prop() method to disable or enable form element or control dynamically using jQuery. The prop() method require jQuery 1.6 and above.
Example:
<script type="text/javascript">
$(document).ready(function(){
$('form input[type="submit"]').prop("disabled", true);
$(".agree").click(function(){
if($(this).prop("checked") == true){
$('form input[type="submit"]').prop("disabled", false);
}
else if($(this).prop("checked") == false){
$('form input[type="submit"]').prop("disabled", true);
}
});
});
</script>
Replace the single quote (') character from a string
Here are a few ways of removing a single '
from a string in python.
str.replace
replace
is usually used to return a string with all the instances of the substring replaced.
"A single ' char".replace("'","")
str.translate
In Python 2
To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.
"A single ' char".translate(None,"'")
In Python 3
You will have to use str.maketrans
"A single ' char".translate(str.maketrans({"'":None}))
re.sub
Regular Expressions using re
are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.
re.sub("'","","A single ' char")
Other Ways
There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string
.
Another final method can be used also (Again not recommended - works only if there is only one occurrence )
no module named zlib
My objective was to create a new Django project from the command line in Ubuntu, like so:
django-admin.py startproject mysite
I have python2.7.5 installed. I got this error:
ImportError: No module named zlib
For hours I could not find a solution, until now!
Here is a link to the solution -
http://doc.biblissima-condorcet.fr/loris-setup-guide-ubuntu-debian
I followed and executed instruction in Section 1.1 and it is working perfectly! It is an easy solution.
Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?
Sometimes, I wonder why people compare AWS to Heroku. AWS is an IAAS( infrastructure as a service) it clearly speaks how robust and calculative the system is. Heroku, on the other hand, is just a SAAS, it is basically just one fraction of AWS services. So why struggle with setting up AWS when you can ship your first product to the prime using Heroku.
Heroku is free, simple and easy to deploy almost all types of stacks to the web. Heroku is specifically built to bypass all the hassles of shipping your application to a live server in less than no time.
Nevertheless, you may want to deploy your application using any of the tutorials from both parties and compare
AWS DOCS and Heroku Docs
How do I generate sourcemaps when using babel and webpack?
On Webpack 2 I tried all 12 devtool options. The following options link to the original file in the console and preserve line numbers. See the note below re: lines only.
https://webpack.js.org/configuration/devtool
devtool best dev options
build rebuild quality look
eval-source-map slow pretty fast original source worst
inline-source-map slow slow original source medium
cheap-module-eval-source-map medium fast original source (lines only) worst
inline-cheap-module-source-map medium pretty slow original source (lines only) best
lines only
Source Maps are simplified to a single mapping per line.
This usually means a single mapping per statement (assuming you author is this way).
This prevents you from debugging execution on statement level and from settings breakpoints on columns of a line.
Combining with minimizing is not possible as minimizers usually only emit a single line.
REVISITING THIS
On a large project I find ... eval-source-map rebuild time is ~3.5s ... inline-source-map rebuild time is ~7s
HTML5 validation when the input type is not "submit"
Either you can change the button type to submit
<button type="submit" onclick="submitform()" id="save">Save</button>
Or you can hide the submit button, keep another button with type="button" and have click event for that button
<form>
<button style="display: none;" type="submit" >Hidden button</button>
<button type="button" onclick="submitForm()">Submit</button>
</form>
How do you beta test an iphone app?
In 2014 along with iOS 8 and XCode 6 apple introduced Beta Testing of iOS App using iTunes Connect.
You can upload your build to iTunes connect and invite testers using their mail id's. You can invite up to 2000 external testers using just their email address. And they can install the beta app through TestFlight
How to create streams from string in Node.Js?
Edit: Garth's answer is probably better.
My old answer text is preserved below.
To convert a string to a stream, you can use a paused through stream:
through().pause().queue('your string').end()
Example:
var through = require('through')
// Create a paused stream and buffer some data into it:
var stream = through().pause().queue('your string').end()
// Pass stream around:
callback(null, stream)
// Now that a consumer has attached, remember to resume the stream:
stream.resume()
How to perform Unwind segue programmatically?
FYI: In order for @Vadim's answer to work with a manual unwind seque action called from within a View Controller you must place the command:
[self performSegueWithIdentifier:(NSString*) identifier sender:(id) sender];
inside of the overriden class method viewDidAppear like so:
-(void) viewDidAppear:(BOOL) animated
{
[super viewDidAppear: animated];
[self performSegueWithIdentifier:@"SomeSegueIdentifier" sender:self];
}
If you put it in other ViewController methods like viewDidLoad or viewWillAppear it will be ignored.
How do I determine the dependencies of a .NET application?
Enable assembly binding logging set the registry value EnableLog in HKLM\Software\Microsoft\Fusion to 1. Note that you have to restart your application (use iisreset) for the changes to have any effect.
Tip: Remember to turn off fusion logging when you are done since there is a performance penalty to have it turned on.
Not showing placeholder for input type="date" field
SO what i have decided to do finally is here and its working fine on all mobile browsers including iPhones and Androids.
_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
$('input[type="date"]').each(function(e) {_x000D_
var $el = $(this), _x000D_
$this_placeholder = $(this).closest('label').find('.custom-placeholder');_x000D_
$el.on('change',function(){_x000D_
if($el.val()){_x000D_
$this_placeholder.text('');_x000D_
}else {_x000D_
$this_placeholder.text($el.attr('placeholder'));_x000D_
}_x000D_
});_x000D_
});_x000D_
_x000D_
});
_x000D_
label {_x000D_
position: relative; _x000D_
}_x000D_
.custom-placeholder {_x000D_
#font > .proxima-nova-light(26px,40px);_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 10;_x000D_
color: #999;_x000D_
}
_x000D_
<label>_x000D_
<input type="date" placeholder="Date">_x000D_
<span class="custom-placeholder">Date</span>_x000D_
</label>
_x000D_
_x000D_
_x000D_
Date
How to display list of repositories from subversion server
If your server is Apache, you should
be able to configure it to see the
repository list with viewvc -
this is the most basic one, other more
complex interfaces exist but this is
not your purpose here.
In some versions, ViewVC is an option of the standard installation
now, for instance from Collabnet.
Edit: Nevermind my previous idea just above, Peter has a much simpler way of sending the repository list.
From there, you will have to:
- get the HTML page,
- extract the list, and
- process it for the individual repository search.
Unfortunately in this case I cannot think of something more straightforward.
There are examples on SO on how to extract text from HTML pages in Python, this would be a good option since Python also has bindings for SVN, to perform the repository search - you can still call svn
directly from Python if you prefer.
If Python is not your cup of tea, you will have to process that differently with GNU tools (wget, then parsing tools or existing packages - I can't be of much help there, Carl gave you some more details in this post).
java.sql.SQLException: Fail to convert to internal representation
I had the same problem and this is my solution. I had the following code:
se.GiftDescription = rs.getString(1);
se.GiftAmount = rs.getInt(2);
And I changed it to:
se.GiftDescription = rs.getString("DESCRIPTION");
se.GiftAmount = rs.getInt("AMOUNT");
And the problem was, after I restarted my PC, the column positions changed. That's why I got this error.