There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).
You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:
Company: Vodafone
------------------
LSE symbol: VOD
in Google: LON:VOD
in Yahoo: VOD.L
NASDAQ symbol: VOD
in Google: NASDAQ:VOD
in Yahoo: VOD
In my case it was the use of the call_command
module that posed a problem.
I added set DJANGO_SETTINGS_MODULE=mysite.settings
but it didn't work.
I finally found it:
add these lines at the top of the script, and the order matters.
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
import django
django.setup()
from django.core.management import call_command
Here it is:
def put4ChannelImageOn4ChannelImage(back, fore, x, y):
rows, cols, channels = fore.shape
trans_indices = fore[...,3] != 0 # Where not transparent
overlay_copy = back[y:y+rows, x:x+cols]
overlay_copy[trans_indices] = fore[trans_indices]
back[y:y+rows, x:x+cols] = overlay_copy
#test
background = np.zeros((1000, 1000, 4), np.uint8)
background[:] = (127, 127, 127, 1)
overlay = cv2.imread('imagee.png', cv2.IMREAD_UNCHANGED)
put4ChannelImageOn4ChannelImage(background, overlay, 5, 5)
Instant.now()
.toString()
2018-02-02T00:28:02.487114Z
Instant.parse(
"2018-02-02T00:28:02.487114Z"
)
The accepted Answer by ppeterka is correct. Your abuse of the formatting pattern results in an erroneous display of data, while the internal value is always limited milliseconds.
The troublesome SimpleDateFormat
and Date
classes you are using are now legacy, supplanted by the java.time classes. The java.time classes handle nanoseconds resolution, much finer than the milliseconds limit of the legacy classes.
The equivalent to java.util.Date
is java.time.Instant
. You can even convert between them using new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Capture the current moment in UTC. Java 8 captures the current moment in milliseconds, while a new Clock
implementation in Java 9 captures the moment in finer granularity, typically microseconds though it depends on the capabilities of your computer hardware clock & OS & JVM implementation.
Instant instant = Instant.now() ;
Generate a String in standard ISO 8601 format.
String output = instant.toString() ;
2018-02-02T00:28:02.487114Z
To generate strings in other formats, search Stack Overflow for DateTimeFormatter
, already covered many times.
To adjust into a time zone other than UTC, use ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
The ORA-2270 error is a straightforward logical error: it happens when the columns we list in the foreign key do not match a primary key or unique constraint on the parent table. Common reasons for this are
Neither appears to be the case in your posted code. But that's a red herring, because your code does not run as you have posted it. Judging from the previous edits I presume you are not posting your actual code but some simplified example. Unfortunately in the process of simplification you have eradicated whatever is causing the ORA-2270 error.
SQL> CREATE TABLE JOB
(
ID NUMBER NOT NULL ,
USERID NUMBER,
CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
); 2 3 4 5 6
Table created.
SQL> CREATE TABLE USER
(
ID NUMBER NOT NULL ,
CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
); 2 3 4 5
CREATE TABLE USER
*
ERROR at line 1:
ORA-00903: invalid table name
SQL>
That statement failed because USER is a reserved keyword so we cannot name a table USER. Let's fix that:
SQL> 1
1* CREATE TABLE USER
SQL> a s
1* CREATE TABLE USERs
SQL> l
1 CREATE TABLE USERs
2 (
3 ID NUMBER NOT NULL ,
4 CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
5* )
SQL> r
1 CREATE TABLE USERs
2 (
3 ID NUMBER NOT NULL ,
4 CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
5* )
Table created.
SQL> Alter Table JOB ADD CONSTRAINT FK_USERID FOREIGN KEY(USERID) REFERENCES USERS(ID);
Table altered.
SQL>
And lo! No ORA-2270 error.
Alas, there's not much we can do here to help you further. You have a bug in your code. You can post your code here and one of us can spot your mistake. Or you can check your own code and discover it for yourself.
Note: an earlier version of the code defined HOB.USERID as VARCHAR2(20). Because USER.ID is defined as a NUMBER the attempt to create a foreign key would have hurl a different error:
ORA-02267: column type incompatible with referenced column type
An easy way to avoid mismatches is to use foreign key syntax to default the datatype of the column:
CREATE TABLE USERs
(
ID number NOT NULL ,
CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
);
CREATE TABLE JOB
(
ID NUMBER NOT NULL ,
USERID constraint FK_USERID references users,
CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
);
You set the CSS to :
#elementID {
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
height: 200px;
}
It centers the image, but does not scale it.
In newer browsers you can use the background-size
property and do:
#elementID {
height: 200px;
width: 100%;
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
background-size: 100% 100%;
}
Other than that, a regular image is one way to do it, but then it's not really a background image.
?
I created a tiny JQuery plugin for this. You may try it:
$.poll('http://my/url', 100, (xhr, status, data) => {
return data.hello === 'world';
})
Try this MSDN blog
Also, try the following example:
Xaml:
<DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
<DataGrid.Columns>
<DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
<DataGridTextColumn Header="Account" IsReadOnly="True" Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
CS:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var data = new Test { Test1 = "Test1", Test2 = "Test2" };
DataGridTest.Items.Add(data);
}
}
public class Test
{
public string Test1 { get; set; }
public string Test2 { get; set; }
}
what about this?
$(this).mouseleave(function(){
var thisUI = $(this);
$('html').click(function(){
thisUI.hide();
$('html').unbind('click');
});
});
I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No
C++11: Yes!
C++11 and onwards has this same feature (called delegating constructors).
The syntax is slightly different from C#:
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};
C++03: No
Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:
You can combine two (or more) constructors via default parameters:
class Foo {
public:
Foo(char x, int y=0); // combines two constructors (char) and (char, int)
// ...
};
Use an init method to share common code:
class Foo {
public:
Foo(char x);
Foo(char x, int y);
// ...
private:
void init(char x, int y);
};
Foo::Foo(char x)
{
init(x, int(x) + 7);
// ...
}
Foo::Foo(char x, int y)
{
init(x, y);
// ...
}
void Foo::init(char x, int y)
{
// ...
}
See the C++FAQ entry for reference.
This would be way easier:
char data [21];
int number_of_bytes_received;
if(Serial.available() > 0)
{
number_of_bytes_received = Serial.readBytesUntil (13,data,20); // read bytes (max. 20) from buffer, untill <CR> (13). store bytes in data. count the bytes recieved.
data[number_of_bytes_received] = 0; // add a 0 terminator to the char array
}
bool result = strcmp (data, "whatever");
// strcmp returns 0; if inputs match.
// http://en.cppreference.com/w/c/string/byte/strcmp
if (result == 0)
{
Serial.println("data matches whatever");
}
else
{
Serial.println("data does not match whatever");
}
If you are trying to get multiple mobile numbers in the same text (re.findall
) then you should probably use the following. It's basically on the same lines as the ones that are already mentioned but it also has special look behind and look ahead assertions so that we don't pick a mobile number immediately preceded or immediately followed by a digit. I've also added 0?
just before capturing the actual mobile number to handle special cases where people prepend 0
to the mobile number.
(?<!\d)(?:\+91|91)?\W*(?P<mobile>[789]\d{9})(?!\d)
You may try it on pythex.org!
So I've been using this and it has worked very well: - it works more like a DROP IF EXISTS but gets the job done
DECLARE
VE_TABLENOTEXISTS EXCEPTION;
PRAGMA EXCEPTION_INIT(VE_TABLENOTEXISTS, -942);
PROCEDURE DROPTABLE(PIS_TABLENAME IN VARCHAR2) IS
VS_DYNAMICDROPTABLESQL VARCHAR2(1024);
BEGIN
VS_DYNAMICDROPTABLESQL := 'DROP TABLE ' || PIS_TABLENAME;
EXECUTE IMMEDIATE VS_DYNAMICDROPTABLESQL;
EXCEPTION
WHEN VE_TABLENOTEXISTS THEN
DBMS_OUTPUT.PUT_LINE(PIS_TABLENAME || ' NOT EXIST, SKIPPING....');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END DROPTABLE;
BEGIN
DROPTABLE('YOUR_TABLE_HERE');
END DROPTABLE;
/
Hope this helps Also reference: PLS-00103 Error in PL/SQL Developer
The simplest way to handle this case is by using getattr()
. You can adapt this example to your needs:
from bs4 import BeautifulSoup
source_html = """
<span class="ratingsDisplay">
<a class="ratingNumber" href="https://www.youtube.com/watch?v=oHg5SJYRHA0" target="_blank" rel="noopener">
<span class="ratingsContent">3.7</span>
</a>
</span>
"""
soup = BeautifulSoup(source_html, "lxml")
my_ratings = getattr(soup.find('span', {"class": "ratingsContent"}), "text", None)
print(my_ratings)
This will find the text element,"3.7"
, within the tag object <span class="ratingsContent">3.7</span>
when it exists, however, default to NoneType
when it does not.
getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise, AttributeError is raised.
There is another item where Fortran is different than C - and potentially faster. Fortran has better optimization rules than C. In Fortran, the evaluation order of an expressions is not defined, which allows the compiler to optimize it - if one wants to force a certain order, one has to use parentheses. In C the order is much stricter, but with "-fast" options, they are more relaxed and "(...)" are also ignored. I think Fortran has a way which lies nicely in the middle. (Well, IEEE makes the live more difficult as certain evaluation-order changes require that no overflows occur, which either has to be ignored or hampers the evaluation).
Another area of smarter rules are complex numbers. Not only that it took until C 99 that C had them, also the rules govern them is better in Fortran; since the Fortran library of gfortran is partially written in C but implements the Fortran semantics, GCC gained the option (which can also be used with "normal" C programs):
-fcx-fortran-rules Complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there is no checking whether the result of a complex multiplication or division is "NaN + I*NaN", with an attempt to rescue the situation in that case.
The alias rules mentioned above is another bonus and also - at least in principle - the whole-array operations, which if taken properly into account by the optimizer of the compiler, can lead faster code. On the contra side are that certain operation take more time, e.g. if one does an assignment to an allocatable array, there are lots of checks necessary (reallocate? [Fortran 2003 feature], has the array strides, etc.), which make the simple operation more complex behind the scenes - and thus slower, but makes the language more powerful. On the other hand, the array operations with flexible bounds and strides makes it easier to write code - and the compiler is usually better optimizing code than a user.
In total, I think both C and Fortran are about equally fast; the choice should be more which language does one like more or whether using the whole-array operations of Fortran and its better portability are more useful -- or the better interfacing to system and graphical-user-interface libraries in C.
The C language doesn't prohibit that kind of #include, but the resulting translation unit still has to be valid C.
I don't know what program you're using with a .prj file. If you're using something like "make" or Visual Studio or whatever, just make sure that you set its list of files to be compiled without the one that can't compile independently.
Sku is an int, can't be defaulted to string "sku". Please check Optional URI Parameters and Default Values
OP here, I have learned a lot more about node since I first asked this question. Though Dmitry's answer was very helpful, what ultimately did it for me is to install node with the correct permissions.
I highly recommend not installing node using any package managers, but rather to compile it yourself so that it resides in a local directory with normal permissions.
This article provides a very clear step-by-step instruction of how to do so:
As an additional note, you may also add markup language for pausing or waiting, I learned this from the iPhone iOS which allows numbers to be stored with extension numbers in the same line. A semi-colon establishes a wait, which will show as a next step upon calling the number. This helps to simplify the workflow of calling numbers with extensions in their board. You press the button shown on the bottom left of the iPhone screen when prompted, and the iPhone will dial it automatically.
<a href="tel:+50225079227;1">Call Now</a>
The pause is entered with a comma ",", allowing a short pause of time for each comma. Once the time has passed, the number after the comma will be dialed automatically
<a href="tel:+50225079227,1">Call Now, you will be automaticlaly transferred</a>
I was facing the same issue, I made below changes and the issue got resolved.
Open watchQueryOptions.d.ts file
\apollo-client\core\watchQueryOptions.d.ts
Change the query type any instead of DocumentNode, Same for mutation
Before:
export interface QueryBaseOptions<TVariables = OperationVariables> {
query: **DocumentNode**;
After:
export interface QueryBaseOptions<TVariables = OperationVariables> {
query: **any**;
classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.
Not supported in IE < 10
Sam's answer gives the reason that default arguments are preferable for constructors rather than overloading. I just want to add that C++-0x will allow delegation from one constructor to another, thereby removing the need for defaults.
console.log()
in java is System.out.println();
to put text on the next line
And System.out.print();
puts text on the same line.
As others have mentioned, the simplest way to preseed a list is with NoneType
objects.
That being said, you should understand the way Python lists actually work before deciding this is necessary.
In the CPython implementation of a list, the underlying array is always created with overhead room, in progressively larger sizes ( 4, 8, 16, 25, 35, 46, 58, 72, 88, 106, 126, 148, 173, 201, 233, 269, 309, 354, 405, 462, 526, 598, 679, 771, 874, 990, 1120, etc)
, so that resizing the list does not happen nearly so often.
Because of this behavior, most list.append()
functions are O(1)
complexity for appends, only having increased complexity when crossing one of these boundaries, at which point the complexity will be O(n)
. This behavior is what leads to the minimal increase in execution time in S.Lott's answer.
Source: Python list implementation
Found this...
bcp "SELECT top 1 BlobText FROM TableName" queryout "C:\DesinationFolder\FileName.txt" -T -c'
If you need to know about different options of bcp flags...
The magic variables %
n contains the arguments used to invoke the file: %0
is the path to the bat-file itself, %1
is the first argument after, %2
is the second and so on.
Since the arguments are often file paths, there is some additional syntax to extract parts of the path. ~d
is drive, ~p
is the path (without drive), ~n
is the file name. They can be combined so ~dp
is drive+path.
%~dp0
is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.
You can also get other kinds of meta info about the file: ~t
is the timestamp, ~z
is the size.
Look here for a reference for all command line commands. The tilde-magic codes are described under for.
Check if db name do not have "_" or "-" that helps in my case
Simplest way is to use PHPMailer and Gmail SMTP. The configuration would be like the below.
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'Email Address';
$mail->Password = 'Email Account Password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
Example script and full source code can be found from here - How to Send Email from Localhost in PHP
I'd like to point out. maybe this just happens to me, HOWEVER, when I use this.removeAllFiles() in dropzone, it fires the event COMPLETE and this blows, what I did was check if the fileData was empty or not so I could actually submit the form.
2 ways:-
1st one Custom Query
@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);
2nd one JPA Query by method
List<User> deleteByLastname(String lastname);
When you go with query by method (2nd way) it will first do a get call
select * from user where last_name = :firstName
Then it will load it in a List Then it will call delete id one by one
delete from user where id = 18
delete from user where id = 19
First fetch list of object, then for loop to delete id one by one
But, the 1st option (custom query),
It's just a single query It will delete wherever the value exists.
Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby
You need to specify the domain:
$('.button1').click(function() {
window.location = 'www.example.com/index.php?id=' + this.id;
});
I'm afraid you've found both possible methods. Google was, at least initially, going to implement a GChat api you could use for a push/pull implementation. Sadly, that library was cut by Android 1.0.
You could use the function that changes the text of span1 to change the text of the others.
As a work around, if you really want it to have a change
event, then don't asign text to span 1. Instead asign an input variable in jQuery, write a change event to it, and whever ur changing the text of span1 .. instead change the value of your input variable, thus firing change event, like so:
var spanChange = $("<input />");
function someFuncToCalculateAndSetTextForSpan1() {
// do work
spanChange.val($newText).change();
};
$(function() {
spanChange.change(function(e) {
var $val = $(this).val(),
$newVal = some*calc-$val;
$("#span1").text($val);
$("#spanWhatever").text($newVal);
});
});
Though I really feel this "work-around", while useful in some aspects of creating a simple change event, is very overextended, and you'd best be making the changes to other spans at the same time you change span1.
I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
I'm targeting API 22, so don't need to explicitly ask for permissions.
According to the Android Studio download page, the SDK comes bundled with Android Studio. It has its own copy when you install Android Studio.
ADT is a plugin for Eclipse. Try reading through that webpage to see if there is something that got missed when installing.
Here is the wording from the site, regarding ADT:
Similar to Eclipse with the ADT Plugin, Android Studio provides integrated Android developer tools for development and debugging.
If you want to record the user navigation so you can test UI and other things, I recommend you to use TestFairy
It allows you to send the apk to some test users by email and see a video with all the sessions in the app and even the app crashes and device stats.
2 month old thread, but better late than never! On 10.6, I have my webserver documents folder set to:
owner:root
group:_www
permission:755
_www is the user that runs apache under Mac OS X. I then added an ACL to allow full permissions to the Administrators group. That way, I can still make any changes with my admin user without having to authenticate as root. Also, when I want to allow the webserver to write to a folder, I can simply chmod to 775, leaving everyone other than root:_www with only read/execute permissions (excluding any ACLs that I have applied)
That worked for me in Swift 5 like a charm, just add it to your viewDidLoad()
self.navigationItem.setHidesBackButton(true, animated: true)
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=db-server;'
'Database=db;'
'Trusted_Connection=yes;')
sql = "SELECT * FROM [mytable] "
cursor.execute(sql)
for r in cursor:
print(r)
// Excuse my beginner's english
There is msgHTML() method, which, also, call IsHTML().
Hrm... name IsHTML
is confusing...
/**
* Create a message from an HTML string.
* Automatically makes modifications for inline images and backgrounds
* and creates a plain-text version by converting the HTML.
* Overwrites any existing values in $this->Body and $this->AltBody
* @access public
* @param string $message HTML message string
* @param string $basedir baseline directory for path
* @param bool $advanced Whether to use the advanced HTML to text converter
* @return string $message
*/
public function msgHTML($message, $basedir = '', $advanced = false)
In order to use local gem repository in a Rails project, follow the steps below:
Check if your gem folder is a git repository (the command is executed in the gem folder)
git rev-parse --is-inside-work-tree
Getting repository path (the command is executed in the gem folder)
git rev-parse --show-toplevel
Setting up a local override for the rails application
bundle config local.GEM_NAME /path/to/local/git/repository
where GEM_NAME
is the name of your gem and /path/to/local/git/repository
is the output of the command in point 2
In your application Gemfile
add the following line:
gem 'GEM_NAME', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
Running bundle install
should give something like this:
Using GEM_NAME (0.0.1) from git://github.com/GEM_NAME/GEM_NAME.git (at /path/to/local/git/repository)
where GEM_NAME
is the name of your gem and /path/to/local/git/repository
from point 2
Finally, run bundle list
, not gem list
and you should see something like this:
GEM_NAME (0.0.1 5a68b88)
where GEM_NAME
is the name of your gem
A few important cases I am observing using:
Rails 4.0.2
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]
Ubuntu 13.10
RubyMine 6.0.3
RubyMine
is not showing local gems as an external library. More information about the bug can be found here and herestop/start
the rails serverIf I am changing the version
of the gem, stopping/starting
the Rails server gives me an error. In order to fix it, I am specifying the gem version in the rails application Gemfile
like this:
gem 'GEM_NAME', '0.0.2', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
You could write a function that runs getElementsByTagName('*'), and returns only those elements with a "data-foo" attribute:
function getAllElementsWithAttribute(attribute)
{
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++)
{
if (allElements[i].getAttribute(attribute) !== null)
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
Then,
getAllElementsWithAttribute('data-foo');
None of the above mentioned solution worked. The one that seemed to work only provide the functionality for just one cell
Recently I had to enter a lot of names and without suggestions, it was a huge pain. I was fortunate enough to have this excel autocomplete add-in to enable the autocompletion. The down side is that you need to enable macro (but you can always turn it off later)
Or with the power of Java 8 Optional, you also can do such trick:
Optional.ofNullable(boolValue).orElse(false)
:)
With JTable.AUTO_RESIZE_OFF
, the table will not change the size of any of the columns for you, so it will take your preferred setting. If it is your goal to have the columns default to your preferred size, except to have the last column fill the rest of the pane, You have the option of using the JTable.AUTO_RESIZE_LAST_COLUMN
autoResizeMode, but it might be most effective when used with TableColumn.setMaxWidth()
instead of TableColumn.setPreferredWidth() for all but the last column.
Once you are satisfied that AUTO_RESIZE_LAST_COLUMN
does in fact work, you can experiment with a combination of TableColumn.setMaxWidth()
and TableColumn.setMinWidth()
using System;
using System.IO;
public class GetwithoutExtension
{
public static void Main()
{
//D:Dir dhould exists in ur system
DirectoryInfo dir1 = new DirectoryInfo(@"D:Dir");
FileInfo [] files = dir1.GetFiles("*xls", SearchOption.AllDirectories);
foreach (FileInfo f in files)
{
string filename = f.Name.ToString();
filename= filename.Replace(".xls", "");
Console.WriteLine(filename);
}
Console.ReadKey();
}
}
Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:
Option Explicit
Dim StdIn: Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
Main()
Sub Main()
Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false
Do until objInputFile.AtEndOfStream
tmpStr = objInputFile.ReadLine
If foundStrMatch(tmpStr)=true Then
If foundFirstMatch = false Then
index = getIndex(tmpStr)
foundFirstMatch = true
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
If index = getIndex(tmpStr) Then
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
ElseIf index < getIndex(tmpStr) Then
index = getIndex(tmpStr)
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
Else
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub
Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function
Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
getIndex = CInt(char1 & char2)
Else
getIndex = CInt(char1)
End If
End Function
Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
foundStrMatch = true
Else
foundStrMatch = false
End If
End Function
This is the original txt file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
And this is the result I'm expecting
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
Just go to httpd.conf file, for ex. under WAMP environment its situated at:
C:\wamp\bin\apache\apache2.2.22\conf\httpd.conf
go to line no. 46 and edit Listen 80
to your requirement for ex.
Listen 8383
newer versions of WAMP uses these 2 lines:
Listen 0.0.0.0:8383
Listen [::0]:8383
Next go to line no. 171 and edit ServerName localhost:80
to your requirement for ex.
ServerName localhost:8383
Restart Apache
and its done !!
Now, you can access with your URL:
http://localhost:8383 or http://192.168.1.1:8383
Hope it helps to people looking for solution here.
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
Well, I made a simple two liner script for this, Its small and does what u want.
Check it http://jsfiddle.net/9RxLM/
Its a jquery solution :D
read it in the docs.
If you return anything but an int
or None
it will be printed to stderr
.
To get just stderr while discarding stdout do:
output=$(python foo.py 2>&1 >/dev/null)
As stated in other answers, label is an inline element. However, you can apply display: inline-block
to the label and then center with text-align
.
#name_label {
display: inline-block;
width: 90%;
text-align: right;
}
Why display: inline-block
and not display: inline
? For the same reason that you can't align label
, it's inline.
Why display: inline-block
and not display: block
? You could use display: block
, but it will be on another line. display: inline-block
combines the properties of inline
and block
. It's inline, but you can also give it a width, height, and align it.
Regarding Jay Stevens answer: "The fonts available to use in an HTML file have to be present on the user's machine and accessible from the web browser, so unless you want to distribute the fonts to the user's machine via a separate external process, it can't be done." That's true.
But there is another way using javascript / canvas / flash - very good solution gives cufon: http://cufon.shoqolate.com/generate/ library that generates a very easy to use external fonts methods.
Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:
slapcat > backup.ldif
If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.
If you really want to process your file line by line, a solution might be to use fgetl
:
fopen
fgetl
sscanf
on the character array you just readUnlike the previous answer, this is not very much in the style of Matlab but it might be more efficient on very large files.
Hope this will help.
On Ubuntu 14.04 I installed it from apt-get and it worked fine:
sudo apt-get install python-beautifulsoup
Then just do:
from BeautifulSoup import BeautifulSoup
Another option is Apache Commons Config also has a class for loading from INI files. It does have some runtime dependencies, but for INI files it should only require Commons collections, lang, and logging.
I've used Commons Config on projects with their properties and XML configurations. It is very easy to use and supports some pretty powerful features.
function resize() {
var map_obj = document.getElementById("map_canvas");
/* map_obj.style.width = "500px";
map_obj.style.height = "225px";*/
if (map) {
map.checkResize();
map.panTo(new GLatLng(lat,lon));
}
}
<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">
</div>
In google chrome element.value return the name + the path, but a fake path. Thus, for my case I used the name attribute on the file like below :
function getFileData(myFile){
var file = myFile.files[0];
var filename = file.name;
}
this is the call from the page :
<input id="ph1" name="photo" type="file" class="jq_req" onchange="getFileData(this);"/>
Um, why not just:
>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'
I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:
Go to folder:
C:\AppServ\MySQL
Right click and Run as Administrator these files:
mysql_servicefix.bat
mysql_serviceinstall.bat
mysql_servicestart.bat
Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.
You can also use this query
USE MASTER
GO
xp_readerrorlog 0, 1, N'Server is listening on'
GO
Source : sqlauthority blog
SOLUTION
Remove the Quotes around the /p:PublishDir setting
i.e.
Instead of quotes
/p:PublishDir="\\BSIIS3\c$\DATA\WEBSITES\benesys.net\benesys.net\TotalEducationTest\"
Use no quotes
/p:PublishDir=\\BSIIS3\c$\DATA\WEBSITES\benesys.net\benesys.net\TotalEducationTest\
I am sorry I did not post my finding sooner. I actually had to research again to see what needed to be changed. Who would have thought removing quotes would have worked? I discovered this when viewing a coworkers build for another solution and noticed it did not have quotes.
From API:
rename_column(table_name, column_name, new_column_name)
It renames a column but keeps the type and content remains same.
For future readers who need this answer quickly:
2^31-1 = 2.147.483.647 characters
If you have the suhosin extension enabled, it can prevent scripts from setting the memory limit beyond what it started with or some defined cap.
http://www.hardened-php.net/suhosin/configuration.html#suhosin.memory_limit
check this out https://forum.jquery.com/topic/get-index-of-same-class-element-on-click then http://jsfiddle.net/me2loveit2/d6rFM/2/
var index = $('selector').index(this);
console.log(index)
Adding only android-support-v7-appcompat.jar
to library dependencies is not enough, you have also to import in your project the module that you can find in your SDK at the path \android-sdk\extras\android\support\v7\appcompat
and after that add module dependencies configuring the project structure in this way
otherwise are included only the class files of support library and the app is not able to load the other resources causing the error.
In addition as reVerse suggested replace this
public CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout,new Toolbar(MyActivity.this) ,
R.string.ns_menu_open, R.string.ns_menu_close);
}
with
public CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}
I wouldn't recommend the HAVING
keyword for newbies, it is essentially for legacy purposes.
I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:
I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.
So I've taken a literal interpretation.
The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES
but it could be a VIEW
:
WITH PAYMENT_TALLIES (user_id, zip, tally)
AS
(
SELECT user_id, zip, COUNT(*) AS tally
FROM PAYMENT
GROUP
BY user_id, zip
)
SELECT DISTINCT *
FROM PAYMENT AS P
WHERE EXISTS (
SELECT *
FROM PAYMENT_TALLIES AS PT
WHERE P.user_id = PT.user_id
AND PT.tally > 1
);
setup.py
is a Python file like any other. It can take any name, except by convention it is named setup.py
so that there is not a different procedure with each script.
Most frequently setup.py
is used to install a Python module but server other purposes:
Modules:
Perhaps this is most famous usage of setup.py
is in modules. Although they can be installed using pip
, old Python versions did not include pip
by default and they needed to be installed separately.
If you wanted to install a module but did not want to install pip
, just about the only alternative was to install the module from setup.py
file. This could be achieved via python setup.py install
. This would install the Python module to the root dictionary (without pip
, easy_install
ect).
This method is often used when pip
will fail. For example if the correct Python version of the desired package is not available via pip
perhaps because it is no longer maintained, , downloading the source and running python setup.py install
would perform the same thing, except in the case of compiled binaries are required, (but will disregard the Python version -unless an error is returned).
Another use of setup.py
is to install a package from source. If a module is still under development the wheel files will not be available and the only way to install is to install from the source directly.
Building Python extensions:
When a module has been built it can be converted into module ready for distribution using a distutils setup script. Once built these can be installed using the command above.
A setup script is easy to build and once the file has been properly configured and can be compiled by running python setup.py build
(see link for all commands).
Once again it is named setup.py
for ease of use and by convention, but can take any name.
Cython:
Another famous use of setup.py
files include compiled extensions. These require a setup script with user defined values. They allow fast (but once compiled are platform dependant) execution. Here is a simple example from the documentation:
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'Hello world app',
ext_modules = cythonize("hello.pyx"),
)
This can be compiled via python setup.py build
Cx_Freeze:
Another module requiring a setup script is cx_Freeze
. This converts Python script to executables. This allows many commands such as descriptions, names, icons, packages to include, exclude ect and once run will produce a distributable application. An example from the documentation:
import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = "guifoo",
version = "0.1",
description = "My GUI application!",
options = {"build_exe": build_exe_options},
executables = [Executable("guifoo.py", base=base)])
This can be compiled via python setup.py build
.
So what is a setup.py
file?
Quite simply it is a script that builds or configures something in the Python environment.
A package when distributed should contain only one setup script but it is not uncommon to combine several together into a single setup script. Notice this often involves distutils
but not always (as I showed in my last example). The thing to remember it just configures Python package/script in some way.
It takes the name so the same command can always be used when building or installing.
All radio buttons inside of a share container are in the same group by default.
Means, if you check one of them - others will be unchecked.
If you want to create independent groups of radio buttons, you must situate them into different containers such as Group Box
, or control their Checked state through code behind.
You can use undocumented method android.app.ActivityThread.currentPackageName()
:
Class<?> clazz = Class.forName("android.app.ActivityThread");
Method method = clazz.getDeclaredMethod("currentPackageName", null);
String appPackageName = (String) method.invoke(clazz, null);
Caveat: This must be done on the main thread of the application.
Thanks to this blog post for the idea: http://blog.javia.org/static-the-android-application-package/ .
Open the CSV file with a decent text editor like Notepad++ and add the following text in the first line:
sep=,
Now open it with excel again.
This will set the separator as a comma, or you can change it to whatever you need.
Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:
If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"
I wound up writing my own command-line tool to take care of this. It's similar to cut
, except it knows what to do with quoted fields, etc. This tool, paired with @Jimothy's answer, allows me to get a headerless CSV from a remote MySQL server I have no filesystem access to onto my local machine with this command:
$ mysql -N -e "select people, places from things" | csvm -i '\t' -o ','
Bill,"Raleigh, NC"
extension to remove String object
extension Array {
mutating func delete(element: String) {
self = self.filter() { $0 as! String != element }
}
}
In XML, this what I use for achieving the same result. May be this is more intuitive.
scale_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<scale
android:duration="200"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:pivotX="50%"
android:pivotY="100%"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
scale_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<scale
android:duration="200"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="100%"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
See the animation on the X axis is from 1.0 -> 1.0
which means you don't have any scaling up in that direction and stays at the full width while, on the Y axis you get 0.0 -> 1.0
scaling, as shown in the graphic in the question. Hope this helps someone.
Some might want to know the java code as we see one requested.
Place the animation files in anim
folder and then load and set animation files something like.
Animation scaleDown = AnimationUtils.loadAnimation(youContext, R.anim.scale_down);
ImagView v = findViewById(R.id.your_image_view);
v.startAnimation(scaleDown);
If your MySQL server process is listening on 127.0.0.1 or ::1 only then you will not be able to connect remotely. If you have a bind-address
setting in /etc/my.cnf
this might be the source of the problem.
You will also have to add privileges for a non-localhost
user as well.
When a process needs to fetch data from a disk, it effectively stops running on the CPU to let other processes run because the operation might take a long time to complete – at least 5ms seek time for a disk is common, and 5ms is 10 million CPU cycles, an eternity from the point of view of the program!
From the programmer point of view (also said "in userspace"), this is called a blocking system call. If you call write(2)
(which is a thin libc wrapper around the system call of the same name), your process does not exactly stop at that boundary; it continues, in the kernel, running the system call code. Most of the time it goes all the way up to a specific disk controller driver (filename ? filesystem/VFS ? block device ? device driver), where a command to fetch a block on disk is submitted to the proper hardware, which is a very fast operation most of the time.
THEN the process is put in sleep state (in kernel space, blocking is called sleeping – nothing is ever 'blocked' from the kernel point of view). It will be awakened once the hardware has finally fetched the proper data, then the process will be marked as runnable and will be scheduled. Eventually, the scheduler will run the process.
Finally, in userspace, the blocking system call returns with proper status and data, and the program flow goes on.
It is possible to invoke most I/O system calls in non-blocking mode (see O_NONBLOCK
in open(2)
and fcntl(2)
). In this case, the system calls return immediately and only report submitting the disk operation. The programmer will have to explicitly check at a later time whether the operation completed, successfully or not, and fetch its result (e.g., with select(2)
). This is called asynchronous or event-based programming.
Most answers here mentioning the D state (which is called TASK_UNINTERRUPTIBLE
in the Linux state names) are incorrect. The D state is a special sleep mode which is only triggered in a kernel space code path, when that code path can't be interrupted (because it would be too complex to program), with the expectation that it would block only for a very short time. I believe that most "D states" are actually invisible; they are very short lived and can't be observed by sampling tools such as 'top'.
You can encounter unkillable processes in the D state in a few situations. NFS is famous for that, and I've encountered it many times. I think there's a semantic clash between some VFS code paths, which assume to always reach local disks and fast error detection (on SATA, an error timeout would be around a few 100 ms), and NFS, which actually fetches data from the network which is more resilient and has slow recovery (a TCP timeout of 300 seconds is common). Read this article for the cool solution introduced in Linux 2.6.25 with the TASK_KILLABLE
state. Before this era there was a hack where you could actually send signals to NFS process clients by sending a SIGKILL to the kernel thread rpciod
, but forget about that ugly trick.…
Just a supplement to the first post: use a user defined union type to store the pthread_t:
union tid {
pthread_t pthread_id;
unsigned long converted_id;
};
Whenever you want to print pthread_t
, create a tid
and assign tid.pthread_id = ...
, then print tid.converted_id
.
We can get a list of files inside a folder on the file system using various golang standard library functions.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
)
func main() {
var (
root string
files []string
err error
)
root := "/home/manigandan/golang/samples"
// filepath.Walk
files, err = FilePathWalkDir(root)
if err != nil {
panic(err)
}
// ioutil.ReadDir
files, err = IOReadDir(root)
if err != nil {
panic(err)
}
//os.File.Readdir
files, err = OSReadDir(root)
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file)
}
}
The
path/filepath
package provides a handy way to scan all the files in a directory, it will automatically scan each sub-directories in the directory.
func FilePathWalkDir(root string) ([]string, error) {
var files []string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
files = append(files, path)
}
return nil
})
return files, err
}
ioutil.ReadDir
reads the directory named by dirname and returns a list of directory entries sorted by filename.
func IOReadDir(root string) ([]string, error) {
var files []string
fileInfo, err := ioutil.ReadDir(root)
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.
func OSReadDir(root string) ([]string, error) {
var files []string
f, err := os.Open(root)
if err != nil {
return files, err
}
fileInfo, err := f.Readdir(-1)
f.Close()
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Benchmark results.
Get more details on this Blog Post
Pure4J supports what you are after, in two ways.
First, it provides an @ImmutableValue
annotation, so that you can annotate a class to say that it is immutable. There is a maven plugin to allow you to check that your code actually is immutable (use of final
etc.).
Second, it provides the persistent collections from Clojure, (with added generics) and ensures that elements added to the collections are immutable. Performance of these is apparently pretty good. Collections are all immutable, but implement java collections interfaces (and generics) for inspection. Mutation returns new collections.
Disclaimer: I'm the developer of this
Check your JAVA_HOME
to use jdk 1.8
Also check : the parameter in Android Studio in order to change at
File->Other Settings->Default Project Structure->SDKs
In phpMyAdmin, navigate to the table in question and click the "Operations" tab. On the left under Table Options you will be allowed to set the current AUTO_INCREMENT value.
"BypassTraverseChecking" means that you can directly access any deep-level subdirectory even if you don't have all the intermediary access privileges to directories in between, i.e. all directories above it towards root level .
If the first segment doesn't start with /
it is a relative route. router.navigate
needs a relativeTo
parameter for relative navigation
Either you make the route absolute:
this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)
or you pass relativeTo
this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})
See also
x = "abcdabcdabcd"
print(x)
l = -1
while True:
l = x.find("a", l+1)
if l == -1:
break
print(l)
As we see (from the answers), there is no standard way for this; and different markdown processors would differ in their markdown extension that offer this kind of possibilities.
With pandoc, you can get what you asked for like this:
Take me to [pookie](#pookie)
...
[this is pookie]{#pookie}
This gives (with pandoc-2.9.2.1):
<p>Take me to <a href="#pookie">pookie</a></p>
<p>…</p>
<p><span id="pookie">this is pookie</span></p>
One can also make an empty span with an anchor id:
Take me to [pookie](#pookie)
...
this is pookie []{#pookie}
which would produce:
<p>Take me to <a href="#pookie">pookie</a></p>
<p>…</p>
<p>this is pookie <span id="pookie"></span></p>
Apart from this, for pandoc and for most common markdown generators, you have a simple self generated anchor in each header. (See that and other answers here for convenient ways to (auto)generate and refernce such anchors.)
To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html
So,
df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
df['C'] = (df['B'] - df['A']).dt.days
which returns:
A B C
one 2014-01-01 2014-02-28 58
two 2014-02-03 2014-03-01 26
git reset --hard can help you if you want to throw away everything since your last commit
I know this is an old Question, but it popped up when I was looking for a solution to the same issue, so I thought that I would post what worked for me.
<asp:BoundField DataField="Description" HeaderText="Bond Event" ItemStyle-Width="300px" />
I used the ItemStyle-Width
attribute on my BoundField
and it worked very nicely I haven't had any issues yet.
I didn't need to add anything else to the rest of the code to make this work either.
If you want tho have a normal string infront of the greek letter make sure that you have the right order:
plt.ylabel(r'Microstrain [$\mu \epsilon$]')
If you're willing to use pandas
:
pandas.DataFrame({'x':hist[1][1:],'y':hist[0]}).plot(x='x',kind='bar')
After opening the file, list comprehension can do this in one line:
fh=open('filename')
newlist = [line.rstrip() for line in fh.readlines()]
fh.close()
Just remember to close your file afterwards.
You can try the following VBA code to export Macro contents directly without converting them to VBA first. Unlike Tables, Forms, Reports, and Modules, the Macros are in a container called Scripts. But they are there and can be exported and imported using SaveAsText and LoadFromText
Option Compare Database
Option Explicit
Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects
Dim db As Database
Dim d As Document
Dim c As Container
Dim sExportLocation As String
Set db = CurrentDb()
sExportLocation = "C:\SomeFolder\"
Set c = db.Containers("Scripts")
For Each d In c.Documents
Application.SaveAsText acMacro, d.Name, sExportLocation & "Macro_" & d.Name & ".txt"
Next d
An alternative object to use is as follows:
For Each obj In Access.Application.CurrentProject.AllMacros
Access.Application.SaveAsText acMacro, obj.Name, strFilePath & "\Macro_" & obj.Name & ".txt"
Next
The accepted answer is great for single renames, but here is a way to rename multiple images that have the same repository all at once (and remove the old images).
If you have old images of the form:
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
old_name/image_name_1 latest abcdefghijk1 5 minutes ago 1.00GB
old_name/image_name_2 latest abcdefghijk2 5 minutes ago 1.00GB
And you want:
new_name/image_name_1
new_name/image_name_2
Then you can use this (subbing in OLD_REPONAME
, NEW_REPONAME
, and TAG
as appropriate):
OLD_REPONAME='old_name'
NEW_REPONAME='new_name'
TAG='latest'
# extract image name, e.g. "old_name/image_name_1"
for image in $(docker images | awk '{ if( FNR>1 ) { print $1 } }' | grep $OLD_REPONAME)
do \
OLD_NAME="${image}:${TAG}" && \
NEW_NAME="${NEW_REPONAME}${image:${#OLD_REPONAME}:${#image}}:${TAG}" && \
docker image tag $OLD_NAME $NEW_NAME && \
docker rmi $image:${TAG} # omit this line if you want to keep the old image
done
This solution uses the hash which is much more performant O(1) than checking if the resides in the array. It has extra safe checks too. Hope it helps.
function uniqueArray(minRange, maxRange, arrayLength) {
var arrayLength = (arrayLength) ? arrayLength : 10
var minRange = (minRange !== undefined) ? minRange : 1
var maxRange = (maxRange !== undefined) ? maxRange : 100
var numberOfItemsInArray = 0
var hash = {}
var array = []
if ( arrayLength > (maxRange - minRange) ) throw new Error('Cannot generate unique array: Array length too high')
while(numberOfItemsInArray < arrayLength){
// var randomNumber = Math.floor(Math.random() * (maxRange - minRange + 1) + minRange)
// following line used for performance benefits
var randomNumber = (Math.random() * (maxRange - minRange + 1) + minRange) << 0
if (!hash[randomNumber]) {
hash[randomNumber] = true
array.push(randomNumber)
numberOfItemsInArray++
}
}
return array
}
document.write(uniqueArray(1, 100, 8))
You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.
Another alternative is that you are allowed to have multiple classes in a tag. Consider:
<div class="button big">This is a big button</div>
<div class="button small">This is a small button</div>
And the CSS:
.button {
/* all your common button styles */
}
.big {
height: 60px;
width: 100px;
}
.small {
height: 40px;
width: 70px;
}
and so on.
if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
"nd"
else
totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')
The above logic should be what you are looking for.
As mentioned you might have a variable named round (of type int
) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.
It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.
<div id="placeholder"></div>
<script id="iframeTemplate" type="text/html">
<iframe src="...">
<!-- replace this line with alternate content -->
</iframe>
</script>
<script type="text/javascript">
var element,
html,
template;
element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;
element.innerHTML = html;
</script>
I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even
SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;
That should work:
function get_content(){
var p = document.getElementById("txt");
var spans = p.getElementsByTagName("span");
var text = '';
for (var i = 0; i < spans.length; i++){
text += spans[i].innerHTML;
}
p.innerHTML = text;
}
Try this fiddle: http://jsfiddle.net/7gnyc/2/
Try this in your script:
$("#YourElement").html(htmlData);
I do this in my table refreshment.
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
Have you tried using Linux Installer to get a full Debian build on the phone? It's billed as being able to run a full LAMP environment in about 300M and has gotten some good reviews.
Here is an answer that should work in all cases:
def is_empty(s):
"Check whether a string is empty"
return not s or not s.strip()
If the variable is None, it will stop at not s
and not evaluate further (since not None == True
). Apparently, the strip()
method takes care of the usual cases of tab, newline, etc.
You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.
I think what you were looking for in your Range was this:
Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete
Just change the column letters to match your needs.
I prefer to work with the PSDrive WSMan:\
.
Get TrustedHosts
Get-Item WSMan:\localhost\Client\TrustedHosts
Set TrustedHosts
provide a single, comma-separated, string of computer names
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'
or (dangerous) a wild-card
Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'
to append to the list, the -Concatenate
parameter can be used
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate
Html Code:
<select id="multiple" multiple="multiple" name="multiple">
<option value=""> -- Select -- </option>
<option value="1">Opt1</option>
<option value="2">Opt2</option>
<option value="3">Opt3</option>
<option value="4">Opt4</option>
<option value="5">Opt5</option>
</select>
JQuery Code:
$('#multiple :selected').each(function(i, sel){
alert( $(sel).val() );
});
Hope it works
In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by()
on distinct("field_name")
queries. This is, however, a Postgres only feature!
If you are using Postgres and if you define a field name that the query should be distinct for, then order_by()
needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).
Note
When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.
For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.
If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:
# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')
In windows 10, most options will not work. Follow these steps:
In Windows 10 with CMD, you cannot download
scipy
directly using most of the well known commands likewget
,cloning scipy github
,pip install scipy
, etcTo install, go to pythonlibs .whl files , and if you are using
python 2.7 32 bit
then downloadnumpy-1.11.2rc1+mkl-cp27-cp27m-win32.whl and scipy-0.18.1-cp27-cp27m-win32.whl
or ifpython 2.7 62 bit
then downloadnumpy-1.11.2rc1+mkl-cp27-cp27m-win_amd64.whl and scipy-0.18.1-cp27-cp27m-win_amd64.whl
After downloading,save the files under your
python directory
, in my case it wasc:\>python27
Then run:
pip install C:\Python27\numpy-1.11.2rc1+mkl-cp27-cp27m-win32.whl
pip install C:\Python27\scipy-0.18.1-cp27-cp27m-win32.whl
Note:
scipy
needs numpy
as dependency, so that's why we are downloading numpy
before scipy
.cp27
in .whl files means that these files are meant for python 2.7
and cp33
stands for python 3.x
speciafically >=3.3This is very nice:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7)
.
There are 10^7 equiprobable (if java.util.Random
is not broken) distinct values so uniqueness may be a concern.
egit has a serious bug when comparing a file in your working dir with an earlier - it flashes a blank tab. The bug has been around since 2010 and still has not been fixed. This very basic feature which works very well in svn plugin is completely broken.
You need the WHERE clause to replace ONLY the records that complies with the condition in the WHERE clause (as opposed to all records). You use % sign to indicate partial string: I.E.
LIKE ('...//domain1.com/images/%');
means all records that BEGIN with "...//domain1.com/images/"
and have anything AFTER (that's the %
for...)
Another example:
LIKE ('%http://domain1.com/images/%')
which means all records that contains "http://domain1.com/images/"
in any part of the string...
You can do something like this
Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();
where you can change "firstname" with the name of the column you want.
Try to disable the engine
option in your .htaccess file:
php_flag engine off
Use datetime.timetuple()
to convert your datetime
object to a time.struct_time
object then get its tm_yday
property:
from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday # returns 1 for January 1st
Type it in one cell, copy that cell, select all the cells you want to fill, and paste.
Alternatively, type it in one cell, select the black square in the bottom-right of that cell, and drag down.
The VirtualPathProviderViewEngine, on which the WebFormsViewEngine is based, is supposed to support the "~" and "/" characters at the front of the path so your examples above should work.
I noticed your examples use the path "~/Account/myPartial.ascx", but you mentioned that your user control is in the Views/Account folder. Have you tried
<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>
or is that just a typo in your question?
If you want to define the date string in strings.xml
. You can do like below.
Calendar.DAY_OF_WEEK
return value from 1 -> 7
<=> Calendar.SUNDAY -> Calendar.SATURDAY
strings.xml
<string-array name="title_day_of_week">
<item>?</item> <!-- sunday -->
<item>?</item> <!-- monday -->
<item>?</item>
<item>?</item>
<item>?</item>
<item>?</item>
<item>?</item> <!-- saturday -->
</string-array>
DateExtension.kt
fun String.getDayOfWeek(context: Context, format: String): String {
val date = SimpleDateFormat(format, Locale.getDefault()).parse(this)
return date?.getDayOfWeek(context) ?: "unknown"
}
fun Date.getDayOfWeek(context: Context): String {
val c = Calendar.getInstance().apply { time = this@getDayOfWeek }
return context.resources.getStringArray(R.array.title_day_of_week)[c[Calendar.DAY_OF_WEEK] - 1]
}
Using
// get current day
val currentDay = Date().getDayOfWeek(context)
// get specific day
val dayString = "2021-1-4"
val day = dayString.getDayOfWeek(context, "yyyy-MM-dd")
Open the mysql terminal:
el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>
Drop the function if it already exists
mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Create the function
mysql> create function hello(id INT)
-> returns CHAR(50)
-> return 'foobar';
Query OK, 0 rows affected (0.01 sec)
Create a simple table to test it out with
mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)
Insert three values into the table yar
mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3 Duplicates: 0 Warnings: 0
Select all the values from yar, run our function hello each time:
mysql> select id, hello(5) from yar;
+------+----------+
| id | hello(5) |
+------+----------+
| 5 | foobar |
| 7 | foobar |
| 9 | foobar |
+------+----------+
3 rows in set (0.01 sec)
Verbalize and internalize what just happened:
You created a function called hello which takes one parameter. The parameter is ignored and returns a CHAR(50)
containing the value 'foobar'. You created a table called yar and added three rows to it. The select statement runs the function hello(5)
for each row returned by yar.
I think that the problem is that you do not have a proper view controller hierarchy. Set the rootviewcontroller of the app and then show new views by pushing or presenting new view controllers on them. Let each view controller manage their views. Only container view controllers, like the tabbarviewcontroller, should ever add other view controllers views to their own views. Read the view controllers programming guide to learn more on how to use view controllers properly. https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/
You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.
$().ready(function () {
$("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
$('some selector', frames['nameOfMyIframe'].document).doStuff();
});
};
The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.
I tried using the the Jack's Asylum cover flow but it wouldn't let me easily remove and re-add an entire coverflow. I eventually found http://finnrudolph.de/ImageFlow and not only is it more reliable, it's easier to hook into, uses less markup, and doesn't jitter when flipping through images. It's by far the best I've found, and I've tried several on this page.
Be explicit - then the compiler won't warn that you perhaps made a mistake.
while ( (list = list->next) != NULL )
or
while ( (list = list->next) )
Some day you'll be glad the compiler told you, people do make that mistake ;)
UPDATE: this is a bug in spring see here
the application properties outside of your jar must be in one of the following places, then everything should work.
21.2 Application property files
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
A /config subdir of the current directory.
The current directory
A classpath /config package
The classpath root
so e.g. this should work, when you dont want to specify cmd line args and you dont use spring.config.location in your base app.props:
d:\yourExecutable.jar
d:\application.properties
or
d:\yourExecutable.jar
d:\config\application.properties
see spring external config doc
Update: you may use \@Configuration together with \@PropertySource. according to the doc here you can specify resources anywhere. you should just be careful, when which config is loaded to make sure your production one wins.
>>> tmp = "a,b,cde"
>>> tmp2 = tmp.split(',')
>>> tmp2.reverse()
>>> "".join(tmp2)
'cdeba'
or simpler:
>>> tmp = "a,b,cde"
>>> ''.join(tmp.split(',')[::-1])
'cdeba'
The important parts here are the split function and the join function. To reverse the list you can use reverse()
, which reverses the list in place or the slicing syntax [::-1]
which returns a new, reversed list.
Just for someone who needs to focus only on Java files, this is my solution:
git diff --name-status SHA1 SHA2 | grep '\.java$'
try this :
driver = webdriver.Chrome(ChromeDriverManager().install())
This might be a better answer copied from this question. Please try it and give opinion here. Please vote up if found useful. Thank you.
<script type="text/javascript">
function generate_excel(tableid) {
var table= document.getElementById(tableid);
var html = table.outerHTML;
window.open('data:application/vnd.ms-excel;base64,' + base64_encode(html));
}
function base64_encode (data) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafal Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['btoa'] == 'function') {
// return btoa(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
</script>
Don't use the IP address to definitively determine location (and hence timezone)-- that's because with NAT, proxies (increasingly popular), and VPNs, IP addresses do not necessarily realistically reflect the user's actual location, but the location at which the servers implementing those protocols reside.
Similar to how US area codes are no longer useful for locating a telephone user, given the popularity of number portability.
IP address and other techniques shown above are useful for suggesting a default that the user can adjust/correct.
A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.
I suggest you reconsider the requirement.
The major browser vendors differ on what "offline" means.
Chrome, Safari, and Firefox (since version 41) will detect when you go "offline" automatically - meaning that "online" events and properties will fire automatically when you unplug your network cable.
Mozilla Firefox (before version 41), Opera, and IE take a different approach, and consider you "online" unless you explicitly pick "Offline Mode" in the browser - even if you don't have a working network connection.
There are valid arguments for the Firefox/Mozilla behavior, which are outlined in the comments of this bug report:
https://bugzilla.mozilla.org/show_bug.cgi?id=654579
But, to answer the question - you can't rely on the online/offline events/property to detect if there is actually network connectivity.
Instead, you must use alternate approaches.
The "Notes" section of this Mozilla Developer article provides links to two alternate methods:
https://developer.mozilla.org/en/Online_and_offline_events
"If the API isn't implemented in the browser, you can use other signals to detect if you are offline including listening for AppCache error events and responses from XMLHttpRequest"
This links to an example of the "listening for AppCache error events" approach:
http://www.html5rocks.com/en/mobile/workingoffthegrid/#toc-appcache
...and an example of the "listening for XMLHttpRequest failures" approach:
http://www.html5rocks.com/en/mobile/workingoffthegrid/#toc-xml-http-request
HTH, -- Chad
In [5]: set(df.Col1).union(set(df.Col2))
Out[5]: {'Bill', 'Bob', 'Joe', 'Mary', 'Steve'}
Or:
set(df.Col1) | set(df.Col2)
This can also be caused if you include bootstrap.js
before jquery.js
.
Others might have the same problem I did.
Include jQuery
before bootstrap
.
You could try the rson library found here: http://code.google.com/p/rson/ . I it also up on PYPI: https://pypi.python.org/pypi/rson/0.9 so you can use easy_install or pip to get it.
for the example given by tom:
>>> rson.loads('[1,2,]')
...
rson.base.tokenizer.RSONDecodeError: Unexpected trailing comma: line 1, column 6, text ']'
RSON is a designed to be a superset of JSON, so it can parse JSON files. It also has an alternate syntax which is much nicer for humans to look at and edit. I use it quite a bit for input files.
As for the capitalizing of boolean values: it appears that rson reads incorrectly capitalized booleans as strings.
>>> rson.loads('[true,False]')
[True, u'False']
mysqldump --extended-insert=FALSE
Be aware that multiple inserts will be slower than one big insert.
As @Bohemian and @mbomb007 mentioned before, this works AND has the additional advantage of being more readable:
console.log(/^(?!.)/s.test("")); //true
You could use overloads:
public static string BuildClause(List<string> l){...}
public static string BuildClause(List<int> l){...}
public static string BuildClause<T>(List<T> l){...}
Or you could inspect the type of the generic parameter:
Type listType = typeof(T);
if(listType == typeof(int)){...}
Here is a tool that generates relational diagrams from MySQL (on Windows at the moment). I have used it on a database with 400 tables. If the diagram is too big for a single diagram, it gets broken down into smaller ones. So you will probably end up with multiple diagrams and you can navigate between them by right clicking. It is all explained in the link below. The tool is free (as in free beer), the author uses it himself on consulting assignments, and lets other people use it. http://www.scmlite.com/Quick%20overview
It's possible to decide which reactor projects to build by specifying the -pl
command line argument:
$ mvn --help
[...]
-pl,--projects <arg> Build specified reactor projects
instead of all projects
[...]
It accepts a comma separated list of parameters in one of the following forms:
[groupId]:artifactId
Thus, given the following structure:
project-root [com.mycorp:parent]
|
+ --- server [com.mycorp:server]
| |
| + --- orm [com.mycorp.server:orm]
|
+ --- client [com.mycorp:client]
You can specify the following command line:
mvn -pl .,server,:client,com.mycorp.server:orm clean install
to build everything. Remove elements in the list to build only the modules you please.
EDIT: as blackbuild pointed out, as of Maven 3.2.1 you have a new -el
flag that excludes projects from the reactor, similarly to what -pl
does:
Flow allows interface specification, without having to convert your whole code base to TypeScript.
Interfaces are a way of breaking dependencies, while stepping cautiously within existing code.
check, if this works for you.
File -> Settings -> (type appe in search box) and select Appearance -> Select Intellij from dropdown option of Theme on the right (under UI Options).
Hope this helps someone.
The difference isn't in performance, but in capability. When using a reference directly you have more power over explicitly using a type of iterator (e.g. List.iterator() vs. List.listIterator(), although in most cases they return the same implementation). You also have the ability to reference the Iterator in your loop. This allows you to do things like remove items from your collection without getting a ConcurrentModificationException.
This is ok:
Set<Object> set = new HashSet<Object>();
// add some items to the set
Iterator<Object> setIterator = set.iterator();
while(setIterator.hasNext()){
Object o = setIterator.next();
if(o meets some condition){
setIterator.remove();
}
}
This is not, as it will throw a concurrent modification exception:
Set<Object> set = new HashSet<Object>();
// add some items to the set
for(Object o : set){
if(o meets some condition){
set.remove(o);
}
}
_x000D_
_x000D_
.custom-modal-header_x000D_
{_x000D_
display: block;_x000D_
}_x000D_
.custom-modal .modal-content_x000D_
{_x000D_
width:500px;_x000D_
border: none;_x000D_
}_x000D_
.custom-modal_x000D_
{_x000D_
display: block !important;_x000D_
}_x000D_
.custom-fade .modal-dialog {_x000D_
transform: translateY(4%);_x000D_
opacity: 0;_x000D_
-webkit-transition: all .2s ease-out;_x000D_
-o-transition: all .2s ease-out;_x000D_
transition: all .2s ease-out;_x000D_
will-change: transform;_x000D_
}_x000D_
.custom-fade.in .modal-dialog {_x000D_
opacity: 1;_x000D_
transform: translateY(0%);_x000D_
}
_x000D_
<div class="modal custom-modal custom-fade" tabindex="-1" role="dialog"_x000D_
aria-hidden="true">_x000D_
<div class="modal-dialog modal-lg">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<h5 class="modal-title">Title</h5>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>My cat is dope.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-primary" data-dismiss="modal">Sure (Meow)</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
I don't understand the concept of storing encrypted stuff in a cookie when it is the encrypted version of it that you need to do your hacking. If I'm missing something, please comment.
I am thinking about taking this approach to 'Remember Me'. If you can see any issues, please comment.
Create a table to store "Remember Me" data in - separate to the user table so that I can log in from multiple devices.
On successful login (with Remember Me ticked):
a) Generate a unique random string to be used as the UserID on this machine: bigUserID
b) Generate a unique random string: bigKey
c) Store a cookie: bigUserID:bigKey
d) In the "Remember Me" table, add a record with: UserID, IP Address, bigUserID, bigKey
If trying to access something that requires login:
a) Check for the cookie and search for bigUserID & bigKey with a matching IP address
b) If you find it, Log the person in but set a flag in the user table "soft login" so that for any dangerous operations, you can prompt for a full login.
On logout, Mark all the "Remember Me" records for that user as expired.
The only vulnerabilities that I can see is;
join this "literal table",
select
t.c.value('@c', 'varchar(30)') code,
t.c.value('@v', 'varchar(30)') val
from (select convert(xml, '<x c="CODE001" v="Value One" /><x c="CODE002" v="Value Two" />') aXmlCol) z
cross apply aXmlCol.nodes('/x') t(c)
You can find the correct dependencies here apply changes to app.gradle and project.gradle and tell me about this, greetings!
Your apply plugin: 'com.google.gms.google-services' in app.gradle looks like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.example.personal.numbermania"
minSdkVersion 10
targetSdkVersion 24
versionCode 1
versionName "1.0"
multiDexEnabled true
}
dexOptions {
incremental true
javaMaxHeapSize "4g" //Here stablished how many cores you want to use your android studi 4g = 4 cores
}
buildTypes {
debug
{
debuggable true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.google.firebase:firebase-ads:9.6.1'
compile 'com.google.firebase:firebase-core:9.6.1'
compile 'com.google.android.gms:play-services:9.6.1'
}
apply plugin: 'com.google.gms.google-services'
Add classpath to the project's gradle:
classpath 'com.google.gms:google-services:3.0.0'
Google play services library on SDK Manager:
In Java nothing is passed by reference. Everything is passed by value. Object references are passed by value. Additionally Strings are immutable. So when you append to the passed String you just get a new String. You could use a return value, or pass a StringBuffer instead.
console.log()
and console.dir()
:Here is the difference in a nutshell:
console.log(input)
: The browser logs in a nicely formatted mannerconsole.dir(input)
: The browser logs just the object with all its propertiesThe following code:
let obj = {a: 1, b: 2};
let DOMel = document.getElementById('foo');
let arr = [1,2,3];
console.log(DOMel);
console.dir(DOMel);
console.log(obj);
console.dir(obj);
console.log(arr);
console.dir(arr);
Logs the following in google dev tools:
Nav.js comp inside components folder
export {Nav}
index.js in component folder
export {Nav} from './Nav';
export {Another} from './Another';
import anywhere
import {Nav, Another} from './components'
As of (at least) macOS 10.12.6 (Sierra) this method seems to have stopped working for Apache httpd (for both the system
and the user
option of launchctl config
). Other programs do not seem to be affected. It is conceivable that this is a bug in httpd.
This concerns OS X 10.10+ (10.11+ specifically due to rootless mode where /usr/bin
is no longer writeable).
I've read in multiple places that using launchctl setenv PATH <new path>
to set the PATH
variable does not work due to a bug in OS X (which seems true from personal experience). I found that there's another way the PATH
can be set for applications not launched from the shell:
sudo launchctl config user path <new path>
This option is documented in the launchctl man page:
config system | user parameter value
Sets persistent configuration information for launchd(8) domains. Only the system domain and user domains may be configured. The location of the persistent storage is an implementation detail, and changes to that storage should only be made through this subcommand. A reboot is required for changes made through this subcommand to take effect.
[...]
path
Sets the PATH environment variable for all services within the target domain to the string value. The string value should conform to the format outlined for the PATH environment variable in environ(7). Note that if a service specifies its own PATH, the service-specific environment variable will take precedence.
NOTE: This facility cannot be used to set general environment variables for all services within the domain. It is intentionally scoped to the PATH environment vari- able and nothing else for security reasons.
I have confirmed this to work with a GUI application started from Finder (which uses getenv
to get PATH).
Note that you only have to do this once and the change will be persistent through reboots.
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
subprocess.call
will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.
import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])
See CNCopyCurrentNetworkInfo in CaptiveNetwork: http://developer.apple.com/library/ios/#documentation/SystemConfiguration/Reference/CaptiveNetworkRef/Reference/reference.html.
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
I have updated accepted answer and removed unnecessary things.
I have created XML for following image.
Your XML code for RadioButton
will be:
<RadioGroup
android:id="@+id/daily_weekly_button_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="@+id/radio0"
android:layout_width="@dimen/_80sdp"
android:gravity="center"
android:layout_height="wrap_content"
android:background="@drawable/radio_flat_selector"
android:button="@android:color/transparent"
android:checked="true"
android:paddingLeft="@dimen/_16sdp"
android:paddingTop="@dimen/_3sdp"
android:paddingRight="@dimen/_16sdp"
android:paddingBottom="@dimen/_3sdp"
android:text="Daily"
android:textColor="@color/radio_flat_text_selector" />
<RadioButton
android:id="@+id/radio1"
android:gravity="center"
android:layout_width="@dimen/_80sdp"
android:layout_height="wrap_content"
android:background="@drawable/radio_flat_selector"
android:button="@android:color/transparent"
android:paddingLeft="@dimen/_16sdp"
android:paddingTop="@dimen/_3sdp"
android:paddingRight="@dimen/_16sdp"
android:paddingBottom="@dimen/_3sdp"
android:text="Weekly"
android:textColor="@color/radio_flat_text_selector" />
</RadioGroup>
radio_flat_selector.xml
for background selector:<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/radio_flat_selected" android:state_checked="true" />
<item android:drawable="@drawable/radio_flat_regular" />
</selector>
radio_flat_selected.xml
for selected button:<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="1dp"
/>
<solid android:color="@color/colorAccent" />
<stroke
android:width="1dp"
android:color="@color/colorAccent" />
</shape>
radio_flat_regular.xml
for regular selector:<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="1dp" />
<solid android:color="#fff" />
<stroke
android:width="1dp"
android:color="@color/colorAccent" />
</shape>
All the above 3 file code will be in drawable/
folder.
Now we also need Text
Color Selector to change color of text accordingly.
radio_flat_text_selector.xml
for text color selector(Use color/
folder for this file.)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/colorAccent" android:state_checked="false" />
<item android:color="@color/colorWhite" android:state_checked="true" />
</selector>
Note: I refereed many answers for this type of solution but didn't found good solution so I make it.
Hope it will be helpful to you.
Thanks.
The problem with taking a given number and displaying it with .ToString("C", culture) is that it effectively changes the amount to the default currency of the given culture. If you have a given amount, the ISO currency code of that amount, and you want to display it for a given culture, I would recommend just creating a decimal extension method like the one below. This will not automatically assume that the currency is in the default currency of the culture:
public static string ToFormattedCurrencyString(
this decimal currencyAmount,
string isoCurrencyCode,
CultureInfo userCulture)
{
var userCurrencyCode = new RegionInfo(userCulture.Name).ISOCurrencySymbol;
if (userCurrencyCode == isoCurrencyCode)
{
return currencyAmount.ToString("C", userCulture);
}
return string.Format(
"{0} {1}",
isoCurrencyCode,
currencyAmount.ToString("N2", userCulture));
}
This will either use the local currency symbol or the ISO currency code with the amount -- whichever is more appropriate. More on the topic in this blog post.
IMHO Lookup tables is the way to go, with referential integrity. But only if you avoid "Evil Magic Numbers" by following an example such as this one: Generate enum from a database lookup table using T4
Have Fun!
One more alternative cross-platform solution on powershell 6.2.3:
$headers = @{
'Authorization' = 'Token 12d119ad48f9b70ed53846f9e3d051dc31afab27'
}
$body = @"
{
"value":"3.92.0",
"product":"847"
}
"@
$params = @{
Uri = 'http://local.vcs:9999/api/v1/version/'
Headers = $headers
Method = 'POST'
Body = $body
ContentType = 'application/json'
}
Invoke-RestMethod @params
Building on dnlbrk's comment, assign can be considerably faster than list2env for big files.
library(readr)
library(stringr)
List_of_file_paths <- list.files(path ="C:/Users/Anon/Documents/Folder_with_csv_files/", pattern = ".csv", all.files = TRUE, full.names = TRUE)
By setting the full.names argument to true, you will get the full path to each file as a separate character string in your list of files, e.g., List_of_file_paths[1] will be something like "C:/Users/Anon/Documents/Folder_with_csv_files/file1.csv"
for(f in 1:length(List_of_filepaths)) {
file_name <- str_sub(string = List_of_filepaths[f], start = 46, end = -5)
file_df <- read_csv(List_of_filepaths[f])
assign( x = file_name, value = file_df, envir = .GlobalEnv)
}
You could use the data.table package's fread or base R read.csv instead of read_csv. The file_name step allows you to tidy up the name so that each data frame does not remain with the full path to the file as it's name. You could extend your loop to do further things to the data table before transferring it to the global environment, for example:
for(f in 1:length(List_of_filepaths)) {
file_name <- str_sub(string = List_of_filepaths[f], start = 46, end = -5)
file_df <- read_csv(List_of_filepaths[f])
file_df <- file_df[,1:3] #if you only need the first three columns
assign( x = file_name, value = file_df, envir = .GlobalEnv)
}
For those using VPS / virtual hosting.
I was using a VPS, getting errors with MySQL not being able to write to /tmp, and everything looked correct. I had enough free space, enough free inodes, correct permissions. Turned out the problem was outside my VPS, it was the machine hosting the VPS that was full. I only had "virtual space" in my file system, but the machine in the background which hosted the VPS had no "physical space" left. I had to contact the VPS company any they fixed it.
If you think this might be your problem, you could test writing a larger file to /tmp (1GB):
dd if=/dev/zero of=/tmp/file.txt count=1024 bs=1048576
I got a No space left on device
error message, which was a giveaway that it was a disk/volume in the background that was full.
I love the Shadow Wizard answer, which accually answers the question pretty nicelly. My jQuery twist on this which i use is here. http://jsfiddle.net/UJAe4/
After typing new value, the form is ready to send, just need to handle new values on the back end.
jQuery is:
(function ($)
{
$.fn.otherize = function (option_text, texts_placeholder_text) {
oSel = $(this);
option_id = oSel.attr('id') + '_other';
textbox_id = option_id + "_tb";
this.append("<option value='' id='" + option_id + "' class='otherize' >" + option_text + "</option>");
this.after("<input type='text' id='" + textbox_id + "' style='display: none; border-bottom: 1px solid black' placeholder='" + texts_placeholder_text + "'/>");
this.change(
function () {
oTbox = oSel.parent().children('#' + textbox_id);
oSel.children(':selected').hasClass('otherize') ? oTbox.show() : oTbox.hide();
});
$("#" + textbox_id).change(
function () {
$("#" + option_id).val($("#" + textbox_id).val());
});
};
}(jQuery));
So you apply this to the below html:
<form>
<select id="otherize_me">
<option value=1>option 1</option>
<option value=2>option 2</option>
<option value=3>option 3</option>
</select>
</form>
Just like this:
$(function () {
$("#otherize_me").otherize("other..", "put new option vallue here");
});
hr {
border: 1px dotted #ff0000;
border-style: none none dotted;
color: #fff;
background-color: #fff;
}
Try this
Install yajl-tools with the command below:
sudo apt-get install yajl-tools
then,
echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat
Here is another solution that does not require the csv
module.
print ', '.join(['"'+i+'"' for i in myList])
Example :
>>> myList = [u'value 1', u'value 2', u'value 3']
>>> print ', '.join(['"'+i+'"' for i in myList])
"value 1", "value 2", "value 3"
However, if the initial list contains some ", they will not be escaped. If it is required, it is possible to call a function to escape it like that :
print ', '.join(['"'+myFunction(i)+'"' for i in myList])
.container {
height: 200px;
position: relative;
border: 3px solid green;
}
.center {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
_x000D_
<h2>Centering Div inside Div, horizontally and vertically without table</h2>
<p>1. Positioning and the transform property to vertically and horizontally center</p>
<p>2. CSS Layout - Horizontal & Vertical Align</p>
<div class="container">
<div class="center">
<p>I am vertically and horizontally centered.</p>
</div>
</div>
_x000D_
To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.
const initialState = {
/* etc */
};
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = initialState;
}
reset() {
this.setState(initialState);
}
/* etc */
}
Beware that the line this.state = initialState;
requires you never to mutate your state, otherwise you'll pollute initialState
and make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialState
in the constructor. (Or make initialState
a function, as per getInitialState()
.)
Finally, I'd recommend you use setState()
and not replaceState()
.
The full procedure that worked for me to transfer ALL branches and tags is, combining the answers of @vikas027 and @kumarahul:
~$ git clone <url_of_old_repo>
~$ cd <name_of_old_repo>
~$ git remote add new-origin <url_of_new_repo>
~$ git push new-origin --mirror
~$ git push new-origin refs/remotes/origin/*:refs/heads/*
~$ git push new-origin --delete HEAD
The last step is because a branch named HEAD
appears in the new remote due to the wildcard
I suppose, you mean converting a list into a numpy array? Then,
import numpy as np
# b is some list, then ...
a = np.array(b).reshape(lengthDim0, lengthDim1);
gives you a as an array of list b in the shape given in reshape.
FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name
A.B
designates a submodule namedB
in a package namedA
....
When importing the package, Python searches through the directories on
sys.path
looking for the package subdirectory.The
__init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such asstring
, from unintentionally hiding valid modules that occur later on the module search path.
You need to set it up to something like this:
man
|- __init__.py
|- Mans
|- __init__.py
|- man1.py
|- MansTest
|- __init.__.py
|- SoftLib
|- Soft
|- __init__.py
|- SoftWork
|- __init__.py
|- manModules.py
|- Unittests
|- __init__.py
|- man1test.py
SECOND, for the "ModuleNotFoundError: No module named 'Soft'
" error caused by from ...Mans import man1
in man1test.py, the documented solution to that is to add man1.py to sys.path
since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path
directly, you can also modify PYTHONPATH
:
sys.path
is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).- The installation-dependent default.
THIRD, for from ...MansTest.SoftLib import Soft
which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.
With that said, here's how I got it to work.
man1.py:
from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH
def foo():
print("called foo in man1.py")
print("foo call module1 from manModules: " + module1())
man1test.py
# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1
man1.foo()
manModules.py
def module1():
return "module1 in manModules"
Terminal output:
$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
...
from ...Mans import man1
File "/temp/man/Mans/man1.py", line 2, in <module>
from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'
$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules
As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).
you can use tcpdump
on the server to check if the client even reaches the server.
tcpdump -i any tcp port 9100
also make sure your firewall is not blocking incoming connections.
EDIT: you can also write the dump into a file and view it with wireshark on your client if you don't want to read it on the console.
2nd Edit: you can check if you can reach the port via
nc ip 9100 -z -v
from your local PC.
You should use npm run-script build
or npm build <project_folder>
. More info here: https://docs.npmjs.com/cli/build.
Try this::
sb_trim = Regex.Replace(stw, @"(\D+)\s+\$([\d,]+)\.\d+\s+(.)",
m => string.Format(
"{0},{1},{2}",
m.Groups[1].Value,
m.Groups[2].Value.Replace(",", string.Empty),
m.Groups[3].Value));
This is about as clean an answer as you'll get, at least with regexes.
(\D+)
: First capture group. One or more non-digit characters.\s+\$
: One or more spacing characters, then a literal dollar sign ($).([\d,]+)
: Second capture group. One or more digits and/or commas.\.\d+
: Decimal point, then at least one digit.\s+
: One or more spacing characters.(.)
: Third capture group. Any non-line-breaking character.The second capture group additionally needs to have its commas stripped. You could do this with another regex, but it's really unnecessary and bad for performance. This is why we need to use a lambda expression and string format to piece together the replacement. If it weren't for that, we could just use this as the replacement, in place of the lambda expression:
"$1,$2,$3"
Based on @Raghuram answer, I find a tutorial on Copying project dependencies, Just:
Open your project pom.xml
file and find this:
<project>
[...]
<build>
<plugins>
...
</plugins>
</build>
[...]
</project>
Than replace the <plugins> ... </plugins>
with:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
And call maven within the command line mvn dependency:copy-dependencies
After it finishes, it will create the folder target/dependency
within all the jar
's dependencies on the current directory where the pom.xml
lives.
If you are using the default theme. Just goto Preferences-> Default File Preferences A new tab pops up. At about line number you could see the font [font-name] [font-size]
Edit the font-size according to your wish and save.
You need to run the .datepicker();
again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});
You are missing a space between else
and if
It should be else if
instead of elseif
if(condition)
{
}
else if(condition)
{
}
else
{
}
this might be repetitive. I was trying to use pycharm to run flask - had anaconda 3, pycharm 2019.1.1 and windows 10. Created a new conda environment - it threw errors. Followed these steps -
Used the cmd to install python and flask after creating environment as suggested above.
Followed this answer.
Obviously kept the correct python interpreter (the one in the environment) everywhere.
Mottie's and Diego Vieira's response above is what we ended up using and should be the accepted answer now. However, before I noticed it, I wrote this little javascript function that doesn't rely on character codes...
var capsLockIsOnKeyDown = {shiftWasDownDuringLastChar: false,
capsLockIsOnKeyDown: function(event) {
var eventWasShiftKeyDown = event.which === 16;
var capsLockIsOn = false;
var shifton = false;
if (event.shiftKey) {
shifton = event.shiftKey;
} else if (event.modifiers) {
shifton = !!(event.modifiers & 4);
}
if (event.target.value.length > 0 && !eventWasShiftKeyDown) {
var lastChar = event.target.value[event.target.value.length-1];
var isAlpha = /^[a-zA-Z]/.test(lastChar);
if (isAlpha) {
if (lastChar.toUpperCase() === lastChar && lastChar.toLowerCase() !== lastChar
&& !event.shiftKey && !capsLockIsOnKeyDown.shiftWasDownDuringLastChar) {
capsLockIsOn = true;
}
}
}
capsLockIsOnKeyDown.shiftWasDownDuringLastChar = shifton;
return capsLockIsOn;
}
}
Then call it in an event handler like so capsLockIsOnKeyDown.capsLockIsOnKeyDown(event)
But again, we ended up just using @Mottie s and @Diego Vieira s response
In order to avoid duplicate code, I recommend you to define the color once, for both states:
a, a:visited{
color: /* some color */;
}
This, indeeed, will mantain your <a>
color (whatever this color is) even when the link has been visited.
Notice that, if the color of the element inside of the <a>
is being inherited (e.g. the color is set in the body
), you could do the following trick:
a, a:visited {
color: inherit;
}
This should be the Unix load average. Wikipedia has a nice article about this.
The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes
You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.
You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig
. It will give out some information and your local IP should look like 192.168.1.x.
from datetime import datetime
start_date = datetime.strptime('8/18/2008', "%m/%d/%Y")
end_date = datetime.strptime('9/26/2008', "%m/%d/%Y")
print abs((end_date-start_date).days)
An alternative way to get only one character.
$str = 'abcdefghij';
echo $str{5};
I would particularly not use this, but for the purpose of education. We can use that to answer the question:
$newString = '';
for ($i = 0; $i < 5; $i++) {
$newString .= $str{$i};
}
echo $newString;
For anyone using that. Bear in mind curly brace syntax for accessing array elements and string offsets is deprecated from PHP 7.4
More information: https://wiki.php.net/rfc/deprecate_curly_braces_array_access
for stylesheets: url(asset_path('image.jpg'))
I would suggest (jQuery needed) :
/*
* windowSize
* call this function to get windowSize any time
*/
function windowSize() {
windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
}
//Init Function of init it wherever you like...
windowSize();
// For example, get window size on window resize
$(window).resize(function() {
windowSize();
console.log('width is :', windowWidth, 'Height is :', windowHeight);
if (windowWidth < 768) {
console.log('width is under 768px !');
}
});
Added in CodePen : http://codepen.io/moabi/pen/QNRqpY?editors=0011
Then you can get easily window's width with the var : windowWidth and Height with : windowHeight
otherwise, get a js library : http://wicky.nillia.ms/enquire.js/
May this one help a little more
Let suppose if you want to make the bar button in a separate file(for modular approach) and want to give selector back to your viewcontroller, you can do like this :-
your Utility File
class GeneralUtility {
class func customeNavigationBar(viewController: UIViewController,title:String){
let add = UIBarButtonItem(title: "Play", style: .plain, target: viewController, action: #selector(SuperViewController.buttonClicked(sender:)));
viewController.navigationController?.navigationBar.topItem?.rightBarButtonItems = [add];
}
}
Then make a SuperviewController class and define the same function on it.
class SuperViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@objc func buttonClicked(sender: UIBarButtonItem) {
}
}
and In our base viewController(which inherit your SuperviewController class) override the same function
import UIKit
class HomeViewController: SuperViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
GeneralUtility.customeNavigationBar(viewController: self,title:"Event");
}
@objc override func buttonClicked(sender: UIBarButtonItem) {
print("button clicked")
}
}
Now just inherit the SuperViewController in whichever class you want this barbutton.
Thanks for the read
You can put them in the Application:
Application["GlobalVar"] = 1234;
They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.
Check your imports. There could be two classes with the same name. Either from your code or from a library you are using. Personally that was the issue.
although it is invalid html but you can use selector context to limit your selector in your case it would be like :
$("input[name='name']" , "#form2").val("Hello World! ");