Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.
Do it like this:
p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)
# get output from process "Something to print"
one_line_output = p.stdout.readline()
# write 'a line\n' to the process
p.stdin.write('a line\n')
# get output from process "not time to break"
one_line_output = p.stdout.readline()
# write "n\n" to that process for if r=='n':
p.stdin.write('n\n')
# read the last output from the process "Exiting"
one_line_output = p.stdout.readline()
What you would do to remove the error:
all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]
But since communicate closes the stdout
and stdin
and stderr
, you can not read or write after you called communicate.
ImageButton \ Button etc.
CommandArgument='<%# Container.DataItemIndex%>'
code-behind
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = e.CommandArgument;
}
Here is an extension method for DirectoryInfo a la FileInfo.CopyTo (note the overwrite
parameter):
public static DirectoryInfo CopyTo(this DirectoryInfo sourceDir, string destinationPath, bool overwrite = false)
{
var sourcePath = sourceDir.FullName;
var destination = new DirectoryInfo(destinationPath);
destination.Create();
foreach (var sourceSubDirPath in Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(sourceSubDirPath.Replace(sourcePath, destinationPath));
foreach (var file in Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories))
File.Copy(file, file.Replace(sourcePath, destinationPath), overwrite);
return destination;
}
Although divmod() has been mentioned, I didn't see what I considered to be a nice example. Here's mine:
q=972021.0000 # For example
days = divmod(q, 86400)
# days[0] = whole days and
# days[1] = seconds remaining after those days
hours = divmod(days[1], 3600)
minutes = divmod(hours[1], 60)
print "%i days, %i hours, %i minutes, %i seconds" % (days[0], hours[0], minutes[0], minutes[1])
Which outputs:
11 days, 6 hours, 0 minutes, 21 seconds
HTML represents meaning; CSS represents appearance. How you mark up text in a document is not determined by how that text appears on screen, but simply what it means. As another example, some other HTML elements, like headings, are styled font-weight: bold
by default, but they are marked up using <h1>
–<h6>
, not <strong>
or <b>
.
In HTML5, you use <strong>
to indicate important parts of a sentence, for example:
<p><strong>Do not touch.</strong> Contains <strong>hazardous</strong> materials.
And you use <em>
to indicate linguistic stress, for example:
<p>A Gentleman: I suppose he does. But there's no point in asking.
<p>A Lady: Why not?
<p>A Gentleman: Because he doesn't row.
<p>A Lady: He doesn't <em>row</em>?
<p>A Gentleman: No. He <em>doesn't</em> row.
<p>A Lady: Ah. I see what you mean.
These elements are semantic elements that just happen to have bold and italic representations by default, but you can style them however you like. For example, in the <em>
sample above, you could represent stress emphasis in uppercase instead of italics, but the functional purpose of the <em>
element remains the same — to change the context of a sentence by emphasizing specific words or phrases over others:
em {
font-style: normal;
text-transform: uppercase;
}
Note that the original answer (below) applied to HTML standards prior to HTML5, in which <strong>
and <em>
had somewhat different meanings, <b>
and <i>
were purely presentational and had no semantic meaning whatsoever. Like <strong>
and <em>
respectively, they have similar presentational defaults but may be styled differently.
You use <strong>
and <em>
to indicate intense emphasis and normal emphasis respectively.
Or think of it this way: font-weight: bold
is closer to <b>
than <strong>
, and font-style: italic
is closer to <i>
than <em>
. These visual styles are purely visual: tools like screen readers aren't going to understand what bold and italic mean, but some screen readers are able to read <strong>
and <em>
text in a more emphasized tone.
A case class is a class that may be used with the match/case
statement.
def isIdentityFun(term: Term): Boolean = term match {
case Fun(x, Var(y)) if x == y => true
case _ => false
}
You see that case
is followed by an instance of class Fun whose 2nd parameter is a Var. This is a very nice and powerful syntax, but it cannot work with instances of any class, therefore there are some restrictions for case classes. And if these restrictions are obeyed, it is possible to automatically define hashcode and equals.
The vague phrase "a recursive decomposition mechanism via pattern matching" means just "it works with case
". (Indeed, the instance followed by match
is compared to (matched against) the instance that follows case
, Scala has to decompose them both, and has to recursively decompose what they are made of.)
What case classes are useful for? The Wikipedia article about Algebraic Data Types gives two good classical examples, lists and trees. Support for algebraic data types (including knowing how to compare them) is a must for any modern functional language.
What case classes are not useful for? Some objects have state, the code like connection.setConnectTimeout(connectTimeout)
is not for case classes.
And now you can read A Tour of Scala: Case Classes
You can use Buffer Reader from request to read
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append(System.lineSeparator());
}
String data = buffer.toString()
I created a simple Objective C wrapper around the good old C array to be used more conveniently: https://gist.github.com/4705733
For normal MySQL, just connect as the 'root' administrative super user, and issue the command:
FLUSH HOSTS
Even in the case of too many connections, MySQL should be keeping a connection in reserve so that a super user can connect.
The mysqladmin
client generally connects as root anyway and issues the above SQL.
To Completely Remove Android Studio from Windows:
Step 1: Run the Android Studio uninstaller
The first step is to run the uninstaller. Open the Control Panel and under Programs, select Uninstall a Program. After that, click on "Android Studio" and press Uninstall. If you have multiple versions, uninstall them as well.
Step 2: Remove the Android Studio files
To delete any remains of Android Studio setting files, in File Explorer, go to your user folder (%USERPROFILE%
), and delete .android
, .AndroidStudio
and any analogous directories with versions on the end, i.e. .AndroidStudio1.2
, as well as .gradle
and .m2
if they exist.
Then go to %APPDATA%
and delete the JetBrains
directory.
Finally, go to C:\Program Files
and delete the Android
directory.
Step 3: Remove SDK
To delete any remains of the SDK, go to %LOCALAPPDATA%
and delete the Android
directory.
Step 4: Delete Android Studio projects
Android Studio creates projects in a folder %USERPROFILE%\AndroidStudioProjects
, which you may want to delete.
There's no supported way to do this, but won't you have to examine the files related to each installer to figure out how to actually install them after extracting them? Assuming you can spend the time to figure out which command-line applies, here are some candidate parameters that normally allow you to extract an installation.
MSI Based (may not result in a usable image for an InstallScript MSI installation):
setup.exe /a /s /v"/qn TARGETDIR=\"choose-a-location\""
or, to also extract prerequisites (for versions where it works),
setup.exe /a"choose-another-location" /s /v"/qn TARGETDIR=\"choose-a-location\""
InstallScript based:
setup.exe /s /extract_all
Suite based (may not be obvious how to install the resulting files):
setup.exe /silent /stage_only ISRootStagePath="choose-a-location"
How about using os.kill? See the docs here: http://docs.python.org/library/os.html#os.kill
$query = "SELECT username, userid FROM user WHERE username = 'admin' ";
$result = $conn->query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$arrayResult = mysql_fetch_array($result);
//Now you can access $arrayResult like this
$arrayResult['userid']; // output will be userid which will be in database
$arrayResult['username']; // output will be admin
//Note- userid and username will be column name of user table.
An integral type representing the smallest value possible. In other words your program should think in cents not in dollars/euros.
This should not stop you from having the gui translate it back to dollars/euros.
Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:
f"({self.goals} goals, ${self.penalties})"
This is similar to the previous .format
standard, but lets one easily do things like:
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result: 12.35'
Just because it is so difficult to find and it has to be spread: in mySQL this can be done much simpler, but I don't know if it works in other SQL.
SELECT * FROM `comments`
WHERE `comments`.`id` IN ('12','5','3','17')
ORDER BY FIELD(`comments`.`id`,'12','5','3','17')
To display the current system date in oracle-sql
select sysdate from dual;
Try this command
npm install github:[Organisation]/[Repository]#[master/BranchName] -g
this command worked for me.
npm install github:BlessCSS/bless#3.x -g
You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)
$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property
Or just this, xpath is case sensitive. Both have the same output:
$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml
Name Type #text
---- ---- -----
DisplayName System.String SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName System.String SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
I went with the direct-approach and just implemented the thing:
public class CollectSingle<T> implements Collector<T, T, T>, BiConsumer<T, T>, Function<T, T>, Supplier<T> {
T value;
@Override
public Supplier<T> supplier() {
return this;
}
@Override
public BiConsumer<T, T> accumulator() {
return this;
}
@Override
public BinaryOperator<T> combiner() {
return null;
}
@Override
public Function<T, T> finisher() {
return this;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
@Override //accumulator
public void accept(T ignore, T nvalue) {
if (value != null) {
throw new UnsupportedOperationException("Collect single only supports single element, "
+ value + " and " + nvalue + " found.");
}
value = nvalue;
}
@Override //supplier
public T get() {
value = null; //reset for reuse
return value;
}
@Override //finisher
public T apply(T t) {
return value;
}
}
with the JUnit test:
public class CollectSingleTest {
@Test
public void collectOne( ) {
List<Integer> lst = new ArrayList<>();
lst.add(7);
Integer o = lst.stream().collect( new CollectSingle<>());
System.out.println(o);
}
@Test(expected = UnsupportedOperationException.class)
public void failOnTwo( ) {
List<Integer> lst = new ArrayList<>();
lst.add(7);
lst.add(8);
Integer o = lst.stream().collect( new CollectSingle<>());
}
}
This implementation not threadsafe.
Try creating a shell script like the one below:
#!/bin/bash
mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7"
You can then add this to the cron
I suppose you want to add a new column in a specific position. You can create a new column by moving current columns to the right.
+---+---+---+
| A | B | C |
+---+---+---+
Remove all affected indexes and foreign key references. Add a new column with the exact same data type like the last column and copy data there.
+---+---+---+---+
| A | B | C | C |
+---+---+---+---+
|___^
Change data type of the third column to the same type like the previous column and copy data there.
+---+---+---+---+
| A | B | B | C |
+---+---+---+---+
|___^
Rename columns accordingly, recreate removed indexes and foreign key references.
+---+---+---+---+
| A | D | B | C |
+---+---+---+---+
Change data type of the second colum.
Keep in mind that the column order is just a "cosmetic" thing like marc_s said.
You can do it with two ways.
First:
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void method(HttpServletResponse httpServletResponse) {
httpServletResponse.setHeader("Location", projectUrl);
httpServletResponse.setStatus(302);
}
Second:
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView method() {
return new ModelAndView("redirect:" + projectUrl);
}
Here is the focus listener example.
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
}
}
});
Don't nest <form>
tags, that will not work. Just use Bootstrap classes.
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="inputType" class="col-md-2 control-label">Type</label>
<div class="col-md-3">
<input type="text" class="form-control" id="inputType" placeholder="Type">
</div>
</div>
<div class="form-group">
<span class="col-md-2 control-label">Metadata</span>
<div class="col-md-6">
<div class="form-group row">
<label for="inputKey" class="col-md-1 control-label">Key</label>
<div class="col-md-2">
<input type="text" class="form-control" id="inputKey" placeholder="Key">
</div>
<label for="inputValue" class="col-md-1 control-label">Value</label>
<div class="col-md-2">
<input type="text" class="form-control" id="inputValue" placeholder="Value">
</div>
</div>
</div>
</div>
</form>
You can achieve that behaviour in many ways, that's just an example. Test it on this bootply
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputType">Type</label>
<div class="controls">
<input type="text" id="inputType" placeholder="Type">
</div>
</div>
<div class="control-group">
<span class="control-label">Metadata</span>
<div class="controls form-inline">
<label for="inputKey">Key</label>
<input type="text" class="input-small" placeholder="Key" id="inputKey">
<label for="inputValue">Value</label>
<input type="password" class="input-small" placeholder="Value" id="inputValue">
</div>
</div>
</form>
Note that I'm using .form-inline
to get the propper styling inside a .controls
.
You can test it on this jsfiddle
Remember, basically and them self doesn't perform any function either. They are not specific about functionality just by their tags.
They can only be customized with the help of CSS.
Now that coming to your question:
SPAN tag together with some styling will be useful on having hold inside a line, say in a paragraph, in the html. This is kind of line level or statement level in HTML.
Example:
<p>Am writing<span class="time">this answer</span> in my free time of my day.</p>
DIV tag functionality as said can only be visible backed with styling, can have hold of large chunks of HTML code.
DIV is Block level
Example:
<div class="large-time">
<p>Am writing <span class="time"> this answer</span> in my free time of my day.
</p>
</div>
Both have their time and case when to be used, based on your requirement.
Hope am clear with the answer. Thank you.
^
matches position just before the first character of the string$
matches position just after the last character of the string.
matches a single character. Does not matter what character it is, except newline*
matches preceding match zero or more timesSo, ^.*$
means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.
Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones
and Matthew's last name is Jones
. The pattern ^Matt.*Jones$
will match Matthew's last name is Jones
. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.
Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.
I try to avoid floating elements unless the design really needs it. Because you have floated the <li>
they are out of normal flow.
If you add .navigation { text-align:center; }
and change .navigation li { float: left; }
to .navigation li { display: inline-block; }
then entire navigation will be centred.
One caveat to this approach is that display: inline-block;
is not supported in IE6 and needs a workaround to make it work in IE7.
What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different...
If it's a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both '\' (Windows) and '/' (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here's a non-RegExp version for extra fun:
var leafname= pathname.split('\\').pop().split('/').pop();
I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)
There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):
The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.
API is really nice and easy to learn. Example how to capture single image and save it to PNG file:
Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
For me the database was not created and EF code first should have created it but always endet in this error. The same connection string was working in aspnet core default web project. The solution was to add
_dbContext.Database.EnsureCreated()
before the first database contact (before DB seeding).
This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.
The code for the button click is below
private void button1_Click(object sender, EventArgs e)
{
New_Form new_Form = new New_Form();
new_Form.Show();
}
Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer
this.Load += new System.EventHandler(this.OnPageLoad);
This OnPageLoad function runs when that form is loaded
In NewForm.cs ,
public partial class New_Form : Form
{
private Timer formClosingTimer;
private void OnPageLoad(object sender, EventArgs e)
{
formClosingTimer = new Timer(); // Creating a new timer
formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
formClosingTimer.Interval = 2000; // Time Interval in miliseconds
formClosingTimer.Start(); // Starting a timer
}
private void CloseForm(object sender, EventArgs e)
{
formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
this.Close(); // Closing the current form
}
}
In this new form , a timer is used to invoke a method which closes that form.
Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.
For your knowledge,
form.close()
will free the memory and we can never interact with that form again
form.hide()
will just hide the form, where the code part can still run
For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2
Assuming code.cpp
is the source code, the following will not throw errors:
make code
./code
Here the first command compiles the code and creates an executable with the same name, and the second command runs it. There is no need to specify g++
keyword in this case.
In Bootstrap 4
In my case I have just changed the .navbar
min-height
and the links font-size
and it decreased the navbar.
For example:
.navbar{
min-height:12px;
}
.navbar a {
font-size: 11.2px;
}
And this also worked for increasing the navbar height.
This also helps to change the navbar size when scrolling down the browser.
Unfortunately, in a cross platform, cross compiler environment, there is no single reliable method to do this purely at compile time.
Therefore, the only reliable method is to combine 3 simple checks:
Choose any method to set the required #define variable. I suggest the method from @JaredPar:
// Check windows
#if _WIN32 || _WIN64
#if _WIN64
#define ENV64BIT
#else
#define ENV32BIT
#endif
#endif
// Check GCC
#if __GNUC__
#if __x86_64__ || __ppc64__
#define ENV64BIT
#else
#define ENV32BIT
#endif
#endif
In main(), double check to see if sizeof() makes sense:
#if defined(ENV64BIT)
if (sizeof(void*) != 8)
{
wprintf(L"ENV64BIT: Error: pointer should be 8 bytes. Exiting.");
exit(0);
}
wprintf(L"Diagnostics: we are running in 64-bit mode.\n");
#elif defined (ENV32BIT)
if (sizeof(void*) != 4)
{
wprintf(L"ENV32BIT: Error: pointer should be 4 bytes. Exiting.");
exit(0);
}
wprintf(L"Diagnostics: we are running in 32-bit mode.\n");
#else
#error "Must define either ENV32BIT or ENV64BIT".
#endif
The general rule is "every #define must end in a #else which generates an error".
#if defined(ENV64BIT)
// 64-bit code here.
#elif defined (ENV32BIT)
// 32-bit code here.
#else
// INCREASE ROBUSTNESS. ALWAYS THROW AN ERROR ON THE ELSE.
// - What if I made a typo and checked for ENV6BIT instead of ENV64BIT?
// - What if both ENV64BIT and ENV32BIT are not defined?
// - What if project is corrupted, and _WIN64 and _WIN32 are not defined?
// - What if I didn't include the required header file?
// - What if I checked for _WIN32 first instead of second?
// (in Windows, both are defined in 64-bit, so this will break codebase)
// - What if the code has just been ported to a different OS?
// - What if there is an unknown unknown, not mentioned in this list so far?
// I'm only human, and the mistakes above would break the *entire* codebase.
#error "Must define either ENV32BIT or ENV64BIT"
#endif
Comment from @AI.G
:
4 years later (don't know if it was possible before) you can convert the run-time check to compile-time one using static assert: static_assert(sizeof(void*) == 4);. Now it's all done at compile time :)
Incidentially, the rules above can be adapted to make your entire codebase more reliable:
The reason why this works well is that it forces you to think of every single case in advance, and not rely on (sometimes flawed) logic in the "else" part to execute the correct code.
I used this technique (among many others) to write a 30,000 line project that worked flawlessly from the day it was first deployed into production (that was 12 months ago).
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
Using UITableViewController
The solution accepted will change the height of the TableViewCell
. To fix that, perform following steps:
Write code snippet given below in ViewDidLoad
method.
tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
Add following method in the TableViewClass.m
file.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return (cell height set on storyboard);
}
That's it. You can build and run your project.
You can add values to the HttpWebRequest.Headers collection.
According to MSDN, it should be supported in windows phone: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers%28v=vs.95%29.aspx
This will return true
if a variable is unset or set to the empty string ("").
if [ -z "$MyVar" ]
then
echo "The variable MyVar has nothing in it."
elif ! [ -z "$MyVar" ]
then
echo "The variable MyVar has something in it."
fi
If you have or are already using lodash, use last instead:
_.last(str);
Not only is it more concise and obvious than the vanilla JS, it also safer since it avoids Uncaught TypeError: Cannot read property X of undefined
when the input is null
or undefined
so you don't need to check this beforehand:
// Will throws Uncaught TypeError if str is null or undefined
str.slice(-1); //
str.charAt(str.length -1);
// Returns undefined when str is null or undefined
_.last(str);
As mentioned above, res.locals is a good (recommended) way to do this. See here for a quick tutorial on how to do this in Express.
You have to declare your functions before main()
(or declare the function prototypes before main()
)
As it is, the compiler sees my_print (my_string);
in main()
as a function declaration.
Move your functions above main()
in the file, or put:
void my_print (char *);
void my_print2 (char *);
Above main()
in the file.
We have only single option left after reading all the fake referrer problems: i.e. The page we desire to track as referrer should be kept in session, and as ajax called then checking in session if it has referrer page value and doing the action other wise no action.
While on the other hand as he request any different page then make the referrer session value to null.
Remember that session variable is set on desire page request only.
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";
//OR
$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
For smaller files you could use this:
& C:\windows\system32\more +1 oldfile.csv > newfile.csv | out-null
... but it's not very effective at processing my example file of 16MB. It doesn't seem to terminate and release the lock on newfile.csv.
If you are using VideoView or heavy weight widgets in your childviews keep your RecyclerView with height wrap_content
inside a NestedScrollView with height match_parent
Then scrolling will work smooth as perfectly as you want it.
FYI,
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:nestedScrollingEnabled="false"
android:layout_height="wrap_content"
android:clipToPadding="false" />
</android.support.v4.widget.NestedScrollView>
Thanks Micro this was from your hint!
karthik
In the jQuery source code we have jQuery.fn = jQuery.prototype = {...}
since jQuery.prototype
is an object the value of jQuery.fn
will simply be a reference to the same object that jQuery.prototype
already references.
To confirm this you can check jQuery.fn === jQuery.prototype
if that evaluates true
(which it does) then they reference the same object
Note that there is a distinction between traditional "beta testing" which is done by professional QA engineers, and "public beta testing" which is releasing your product to the public before it's ready : )
You can do "beta testing" -- loading to specific iPhones/iPods your testers will be using. You can't do "public beta testing" -- pre-releasing to the public.
You could do this two different ways. One is by using "as"
has_many :tasks, :as => :jobs
or
def jobs
self.tasks
end
Obviously the first one would be the best way to handle it.
As suggested by A Star, I always use something along the lines of:
DATE(NOW()) - INTERVAL 1 MONTH
Similarly you can do:
NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY
and so on. Much easier than typing DATE_ADD
or DATE_SUB
all the time :)!
In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:
import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array
res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])
which can be extended to D dimensions.
The results are:
Prediction:
[[1 2]
[2 0]
[2 0]
[1 2]
[1 2]]
Target:
[[0 1]
[1 0]
[2 0]
[0 0]
[2 1]]
Count of correct prediction for D=1: 1
Count of correct prediction for D=2: 2
What is webpack & webpack-dev-server? Official documentation says it's a module bundler but for me it's just a task runner. What's the difference?
webpack-dev-server is a live reloading web server that Webpack developers use to get immediate feedback what they do. It should only be used during development.
This project is heavily inspired by the nof5 unit test tool.
Webpack as the name implies will create a SINGLE package for the web. The package will be minimized, and combined into a single file (we still live in HTTP 1.1 age). Webpack does the magic of combining the resources (JavaScript, CSS, images) and injecting them like this: <script src="assets/bundle.js"></script>
.
It can also be called module bundler because it must understand module dependencies, and how to grab the dependencies and to bundle them together.
Where would you use browserify? Can't we do the same with node/ES6 imports?
You could use Browserify on the exact same tasks where you would use Webpack. – Webpack is more compact, though.
Note that the ES6 module loader features in Webpack2 are using System.import, which not a single browser supports natively.
When would you use gulp/grunt over npm + plugins?
You can forget Gulp, Grunt, Brokoli, Brunch and Bower. Directly use npm command line scripts instead and you can eliminate extra packages like these here for Gulp:
var gulp = require('gulp'),
minifyCSS = require('gulp-minify-css'),
sass = require('gulp-sass'),
browserify = require('gulp-browserify'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
jshint = require('gulp-jshint'),
jshintStyle = require('jshint-stylish'),
replace = require('gulp-replace'),
notify = require('gulp-notify'),
You can probably use Gulp and Grunt config file generators when creating config files for your project. This way you don't need to install Yeoman or similar tools.
Other regex answers in this page will accept an IP with a number over 255.
This regex will avoid this problem:
import re
def validate_ip(ip_str):
reg = r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
if re.match(reg, ip_str):
return True
else:
return False
First, one should check if the last character is a comma. If it exists, remove it.
if (str.indexOf(',', this.length - ','.length) !== -1) {
str = str.substring(0, str.length - 1);
}
NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)
Can't you originally get the data as a JSONObject?
Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?
I'm not sure that it is possible to convert a JsonArray into a JsonObject.
I presume you are using the following from json.org
JSONObject.java
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONArray.java
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
Remove the library from your Podfile
Run pod install
on the terminal
You can also search for the file. Navigate to your project directory with PowerShell and run Get-FileMissingRoot:
function Get-FileMissingRoot {
dir -recurse |
where {
($_ -is [IO.FileInfo]) -and
(@(".xml", ".config") -contains $_.extension)
} |
foreach {
$xml = New-Object Xml.XmlDocument;
$filename = $_.FullName
try {
$xml.Load($filename)
}
catch {
write ("File: " + $filename)
write ($_.Exception.Message)
}
}
}
This is my own plugin (will position the element in top of the the list. Specially for overflow-y : auto
. May not work with overflow-x
!):
NOTE: elem
is the HTML selector of an element which the page will be scrolled to. Anything supported by jQuery, like: #myid
, div.myclass
, $(jquery object)
, [dom object], etc.
jQuery.fn.scrollTo = function(elem, speed) {
$(this).animate({
scrollTop: $(this).scrollTop() - $(this).offset().top + $(elem).offset().top
}, speed == undefined ? 1000 : speed);
return this;
};
If you don't need it to be animated, then use:
jQuery.fn.scrollTo = function(elem) {
$(this).scrollTop($(this).scrollTop() - $(this).offset().top + $(elem).offset().top);
return this;
};
How to use:
$("#overflow_div").scrollTo("#innerItem");
$("#overflow_div").scrollTo("#innerItem", 2000); //custom animation speed
Note: #innerItem
can be anywhere inside #overflow_div
. It doesn't really have to be a direct child.
Tested in Firefox (23) and Chrome (28).
If you want to scroll the whole page, check this question.
The Java Packager tool compiles, packages, and prepares Java and JavaFX applications for distribution. The javapackager command is the command-line version.
– Oracle's documentation
The javapackager
utility ships with the JDK. It can generate .exe files with the -native exe
flag, among many other things.
WinRun4j is a java launcher for windows. It is an alternative to javaw.exe and provides the following benefits:
- Uses an INI file for specifying classpath, main class, vm args, program args.
- Custom executable name that appears in task manager.
- Additional JVM args for more flexible memory use.
- Built-in icon replacer for custom icon.
- [more bullet points follow]
– WinRun4J's webpage
WinRun4J is an open source utility. It has many features.
Packages your JAR, assets and a JVM for distribution on Windows, Linux and Mac OS X, adding a native executable file to make it appear like a native app. Packr is most suitable for GUI applications.
– packr README
packr is another open source tool.
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself.
– JSmooth's website
JSmooth is open source and has features, but it is very old. The last release was in 2007.
JexePack is a command line tool (great for automated scripting) that allows you to package your Java application (class files), optionally along with its resources (like GIF/JPG/TXT/etc), into a single compressed 32-bit Windows EXE, which runs using Sun's Java Runtime Environment. Both console and windowed applications are supported.
– JexePack's website
JexePack is trialware. Payment is required for production use, and exe files created with this tool will display "reminders" without payment. Also, the last release was in 2013.
InstallAnywhere makes it easy for developers to create professional installation software for any platform. With InstallAnywhere, you’ll adapt to industry changes quickly, get to market faster and deliver an engaging customer experience. And know the vulnerability of your project’s OSS components before you ship.
– InstallAnywhere's website
InstallAnywhere is a commercial/enterprise package that generates installers for Java-based programs. It's probably capable of creating .exe files.
As an alternative to .exe files, you can create a JAR file that automatically runs when double-clicked, by adding an entry point to the JAR manifest.
An excellent source of information on this topic is Excelsior's article "Convert Java to EXE – Why, When, When Not and How".
See also the companion article "Best JAR to EXE Conversion Tools, Free and Commercial".
I think I have a solution to what the originator of this inquiry wanted in simple form. It works for me and actually it is the reason I came on here to begin with. I believe just using parentheses around the column like '%text%' in combination with OR
s will do it.
select * from tableName
where (sameColumnName like '%findThis%' or sameColumnName like '%andThis%' or
sameColumnName like '%thisToo%' or sameColumnName like '%andOneMore%')
This worked for me, based on your code, generating a 93Mb png image with color noise and the desired dimensions:
import matplotlib.pyplot as plt
import numpy
w = 7195
h = 3841
im_np = numpy.random.rand(h, w)
fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(im_np, aspect='normal')
fig.savefig('figure.png', dpi=1)
I am using the last PIP versions of the Python 2.7 libraries in Linux Mint 13.
Hope that helps!
$ ls -ld directory
ls
is the list command.
-
indicates the beginning of the command options.
l
asks for a long list which includes the permissions.
d
indicates that the list should concern the named directory itself; not its contents. If no directory name is given, the list output will pertain to the current directory.
Since the MemberwiseClone() method is not public, I created this simple extension method in order to make it easier to clone objects:
public static T Clone<T>(this T obj)
{
var inst = obj.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
return (T)inst?.Invoke(obj, null);
}
Usage:
var clone = myObject.Clone();
You need to set the scope of the dependency to 'provided' in your POM.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
Then everything will be fine.
Add PrivacyBadger to the list of potential causes
This is the result of ifconfig:
pi@raspberrypi:~ $ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.2.24 netmask 255.255.255.0 broadcast 192.168.2.255
inet6 fe80::88e9:4d2:c057:2d5f prefixlen 64 scopeid 0x20<link>
ether b8:27:eb:d0:9a:f3 txqueuelen 1000 (Ethernet)
RX packets 261861 bytes 250818555 (239.1 MiB)
RX errors 0 dropped 6 overruns 0 frame 0
TX packets 299436 bytes 280053853 (267.0 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 74 bytes 16073 (15.6 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 74 bytes 16073 (15.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
wlan0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
ether b8:27:eb:85:cf:a6 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
pi@raspberrypi:~ $
Cutting a bit the output, we have:
pi@raspberrypi:~ $
pi@raspberrypi:~ $ ifconfig eth0 | grep "inet 192" | cut -c 14-25
192.168.2.24
pi@raspberrypi:~ $
pi@raspberrypi:~ $
Now, we can go to python and do:
import os
mine = os.popen('ifconfig eth0 | grep "inet 192" | cut -c 14-25')
myip = mine.read()
print (myip)
document.getElementById('hello').classList.add('someClass');
The .add
method will only add the class if it doesn't already exist on the element. So no need to worry about duplicate class names.
I had the same issue but I solved it by correcting my form open as shown below :
{!!Form::open(['url'=>route('auth.login-post'),'class'=>'form-horizontal'])!!}
If this doesn't solve your problem, can you please show how you opened the form ?
var str = 'Hello World';
str = setCharAt(str, 3, '');
alert(str);
function setCharAt(str, index, chr)
{
if (index > str.length - 1) return str;
return str.substr(0, index) + chr + str.substr(index + 1);
}
HTML:
<a id="hidden_link" href="LinkToImage"></a>
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#hidden_link").fancybox().trigger('click');
});
</script>
$gender = $_POST['gender'];
echo $gender;
it will echoes the selected value.
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
To get your radio button to list horizontally , just add
RepeatDirection="Horizontal"
to your .aspx file where the asp:radiobuttonlist is being declared.
Use scrollTop() to get or set the scroll position.
Currently (June 2016) typing in the link as http://www.example.com will only produce plain text.
You can now however put in an html anchor :
<a href="http://www.example.com">My Example Site</a>
You can create a button in window1 and double click on it. It will create a new click handler, where inside you can write something like this:
var window2 = new Window2();
window2.Show();
You can also add linker flags to a specific target using the LINK_FLAGS
property:
set_property(TARGET ${target} APPEND_STRING PROPERTY LINK_FLAGS " ${flag}")
If you want to propagate this change to other targets, you can create a dummy target to link to.
if the database is InnoDB you dont need to do joins in deletion. only
DELETE FROM spawnlist WHERE spawnlist.type = "monster";
can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.
CREATE TABLE IF NOT EXIST spawnlist (
npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXIST npc (
idTemplate VARCHAR(20) NOT NULL,
FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE
)ENGINE=InnoDB;
if you uses MyISAM you can delete records joining like this
DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';
in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.
In case of a range
or any other linearly increasing array you can simply calculate the index programmatically, no need to actually iterate over the array at all:
def first_index_calculate_range_like(val, arr):
if len(arr) == 0:
raise ValueError('no value greater than {}'.format(val))
elif len(arr) == 1:
if arr[0] > val:
return 0
else:
raise ValueError('no value greater than {}'.format(val))
first_value = arr[0]
step = arr[1] - first_value
# For linearly decreasing arrays or constant arrays we only need to check
# the first element, because if that does not satisfy the condition
# no other element will.
if step <= 0:
if first_value > val:
return 0
else:
raise ValueError('no value greater than {}'.format(val))
calculated_position = (val - first_value) / step
if calculated_position < 0:
return 0
elif calculated_position > len(arr) - 1:
raise ValueError('no value greater than {}'.format(val))
return int(calculated_position) + 1
One could probably improve that a bit. I have made sure it works correctly for a few sample arrays and values but that doesn't mean there couldn't be mistakes in there, especially considering that it uses floats...
>>> import numpy as np
>>> first_index_calculate_range_like(5, np.arange(-10, 10))
16
>>> np.arange(-10, 10)[16] # double check
6
>>> first_index_calculate_range_like(4.8, np.arange(-10, 10))
15
Given that it can calculate the position without any iteration it will be constant time (O(1)
) and can probably beat all other mentioned approaches. However it requires a constant step in the array, otherwise it will produce wrong results.
A more general approach would be using a numba function:
@nb.njit
def first_index_numba(val, arr):
for idx in range(len(arr)):
if arr[idx] > val:
return idx
return -1
That will work for any array but it has to iterate over the array, so in the average case it will be O(n)
:
>>> first_index_numba(4.8, np.arange(-10, 10))
15
>>> first_index_numba(5, np.arange(-10, 10))
16
Even though Nico Schlömer already provided some benchmarks I thought it might be useful to include my new solutions and to test for different "values".
The test setup:
import numpy as np
import math
import numba as nb
def first_index_using_argmax(val, arr):
return np.argmax(arr > val)
def first_index_using_where(val, arr):
return np.where(arr > val)[0][0]
def first_index_using_nonzero(val, arr):
return np.nonzero(arr > val)[0][0]
def first_index_using_searchsorted(val, arr):
return np.searchsorted(arr, val) + 1
def first_index_using_min(val, arr):
return np.min(np.where(arr > val))
def first_index_calculate_range_like(val, arr):
if len(arr) == 0:
raise ValueError('empty array')
elif len(arr) == 1:
if arr[0] > val:
return 0
else:
raise ValueError('no value greater than {}'.format(val))
first_value = arr[0]
step = arr[1] - first_value
if step <= 0:
if first_value > val:
return 0
else:
raise ValueError('no value greater than {}'.format(val))
calculated_position = (val - first_value) / step
if calculated_position < 0:
return 0
elif calculated_position > len(arr) - 1:
raise ValueError('no value greater than {}'.format(val))
return int(calculated_position) + 1
@nb.njit
def first_index_numba(val, arr):
for idx in range(len(arr)):
if arr[idx] > val:
return idx
return -1
funcs = [
first_index_using_argmax,
first_index_using_min,
first_index_using_nonzero,
first_index_calculate_range_like,
first_index_numba,
first_index_using_searchsorted,
first_index_using_where
]
from simple_benchmark import benchmark, MultiArgument
and the plots were generated using:
%matplotlib notebook
b.plot()
b = benchmark(
funcs,
{2**i: MultiArgument([0, np.arange(2**i)]) for i in range(2, 20)},
argument_name="array size")
The numba function performs best followed by the calculate-function and the searchsorted function. The other solutions perform much worse.
b = benchmark(
funcs,
{2**i: MultiArgument([2**i-2, np.arange(2**i)]) for i in range(2, 20)},
argument_name="array size")
For small arrays the numba function performs amazingly fast, however for bigger arrays it's outperformed by the calculate-function and the searchsorted function.
b = benchmark(
funcs,
{2**i: MultiArgument([np.sqrt(2**i), np.arange(2**i)]) for i in range(2, 20)},
argument_name="array size")
This is more interesting. Again numba and the calculate function perform great, however this is actually triggering the worst case of searchsorted which really doesn't work well in this case.
Another interesting point is how these function behave if there is no value whose index should be returned:
arr = np.ones(100)
value = 2
for func in funcs:
print(func.__name__)
try:
print('-->', func(value, arr))
except Exception as e:
print('-->', e)
With this result:
first_index_using_argmax
--> 0
first_index_using_min
--> zero-size array to reduction operation minimum which has no identity
first_index_using_nonzero
--> index 0 is out of bounds for axis 0 with size 0
first_index_calculate_range_like
--> no value greater than 2
first_index_numba
--> -1
first_index_using_searchsorted
--> 101
first_index_using_where
--> index 0 is out of bounds for axis 0 with size 0
Searchsorted, argmax, and numba simply return a wrong value. However searchsorted
and numba
return an index that is not a valid index for the array.
The functions where
, min
, nonzero
and calculate
throw an exception. However only the exception for calculate
actually says anything helpful.
That means one actually has to wrap these calls in an appropriate wrapper function that catches exceptions or invalid return values and handle appropriately, at least if you aren't sure if the value could be in the array.
Note: The calculate and searchsorted
options only work in special conditions. The "calculate" function requires a constant step and the searchsorted requires the array to be sorted. So these could be useful in the right circumstances but aren't general solutions for this problem. In case you're dealing with sorted Python lists you might want to take a look at the bisect module instead of using Numpys searchsorted.
To solve this without jQuery .each()
you'd have to fix your code like this:
var listItems = $("#productList").find("li");
var ind, len, product;
for ( ind = 0, len = listItems.length; ind < len; ind++ ) {
product = $(listItems[ind]);
// ...
}
Bugs in your original code:
for ... in
will also loop through all inherited properties; i.e. you will also get a list of all functions that are defined by jQuery.
The loop variable li
is not the list item, but the index to the list item. In that case the index is a normal array index (i.e. an integer)
Basically you are save to use .each()
as it is more comfortable, but espacially when you are looping bigger arrays the code in this answer will be much faster.
For other alternatives to .each()
you can check out this performance comparison:
http://jsperf.com/browser-diet-jquery-each-vs-for-loop
You can get active store information like this:
Mage::app()->getStore(); // for store object
Mage::app()->getStore()->getStoreId; // for store ID
You can use Series.isin
:
df = df[~df.datecolumn.isin(a)]
While the error message suggests that all()
or any()
can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).
You can read more about this in the Gotchas.
You can use Enum.GetNames to return an IEnumerable of values in your enum and then .Count the resulting IEnumerable.
GetNames produces much the same result as GetValues but is faster.
SELECT t1.cname, t1.wmname, t2.max
FROM makerar t1 JOIN (
SELECT cname, MAX(avg) max
FROM makerar
GROUP BY cname ) t2
ON t1.cname = t2.cname AND t1.avg = t2.max;
Using rank()
window function:
SELECT cname, wmname, avg
FROM (
SELECT cname, wmname, avg, rank()
OVER (PARTITION BY cname ORDER BY avg DESC)
FROM makerar) t
WHERE rank = 1;
Note
Either one will preserve multiple max values per group. If you want only single record per group even if there is more than one record with avg equal to max you should check @ypercube's answer.
Good news everybody! Craigslist has actually released a bulk posting api now!
Look at www.goo.gl/2SIOJj it is a work in progress but it may help you.
I use cookie to define if i want desktop or responsive version. In the footer of the page you can find two spans and in general.js is the script to handle the clicks.
<div class="col-xs-6" style="text-align:center;"><span class="make_desktop">Desktop</span></div>
<div class="col-xs-6" style="text-align:center;"><span class="make_responsive">Mobile</span></div>
function setMobDeskCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value + "; path=/";
window.location.reload();
}
$(function() {
$(".make_desktop").click(function() {
setMobDeskCookie('deskmob', 1, 3650);
});
$(".make_responsive").click(function() {
setMobDeskCookie('deskmob', 0, 3650);
});
});`enter code here`
i ended up splitting all my custom css into two files i don't use bootstrap navigation but my own so that is majority of my custom styles, so it will not resolve your entire problem but it works for me
and i also created non-responsive.css that forces the grid to maintain the large screen version
in case u select mobile i would load / echo
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
and load these stylesheets
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style-responsive.css?modified=1402758346" />
in case you select desktop i would load /echo
<meta name="viewport" content="width=1024">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
<!-- Main CSS -->
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/non-responsive.css?modified=1402758635" />
the non-responsive.css is the one that has overrides for bootstrap my concern is layout so there is not much in there, given that i handle the navigation in my own way so css for it and the other bits is in my other css files
please note that my setup does behave as desktop even on desktop browsers unlike some other solutions i have seen that will only ignore the viewport that seems to have wotked only on mobile devices for me
I am late for the party. Try replacing as below, mine worked perfectly- "DOMDocument" to "MSXML2.DOMDocument60" "XMLHTTP" to "MSXML2.XMLHTTP60"
A few considerations on the subject:
The parenthesis:
The browser (engine/parser) associates the keyword function with
[optional name]([optional parameters]){...code...}
So in an expression like function(){}() the last parenthesis makes no sense.
Now think at
name=function(){} ; name() !?
Yes, the first pair of parenthesis force the anonymous function to turn into a variable (stored expression) and the second launches evaluation/execution, so ( function(){} )() makes sense.
The utility: ?
For executing some code on load and isolate the used variables from the rest of the page especially when name conflicts are possible;
Replace eval("string") with
(new Function("string"))()
Wrap long code for " =?: " operator like:
result = exp_to_test ? (function(){... long_code ...})() : (function(){...})();
To avoid nesting and ngSwitch, there is also this possibility, which leverages the way logical operators work in Javascript:
<ng-container *ngIf="foo === 1; then first; else (foo === 2 && second) || (foo === 3 && third)"></ng-container>
<ng-template #first>First</ng-template>
<ng-template #second>Second</ng-template>
<ng-template #third>Third</ng-template>
You could pass in the command-line option -v
with a variable name (v
) and a value (=
) of the environment variable ("${v}"
):
% awk -vv="${v}" 'BEGIN { print v }'
123test
Or to make it clearer (with far fewer v
s):
% environment_variable=123test
% awk -vawk_variable="${environment_variable}" 'BEGIN { print awk_variable }'
123test
A one-liner option is:
echo date_create('2011-04-24')->modify('-1 days')->format('Y-m-d');
Running it on Online PHP Editor.
If you prefer to avoid using string methods, or going into calculations, or even creating additional variables, mktime supports subtraction and negative values in the following way:
// Today's date
echo date('Y-m-d'); // 2016-03-22
// Yesterday's date
echo date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")-1, date("Y"))); // 2016-03-21
// 42 days ago
echo date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")-42, date("Y"))); // 2016-02-09
//Using a previous date object
$date_object = new DateTime('2011-04-24');
echo date('Y-m-d',
mktime(0, 0, 0,
$date_object->format("m"),
$date_object->format("d")-1,
$date_object->format("Y")
)
); // 2011-04-23
for f in *.png; do
fnew=`echo $f | sed 's/_h.png/_half.png/'`
mv $f $fnew
done
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
Hopes this makes it find the tables as you're reading through the thing:
mysql> show columns from colors;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| color | varchar(15) | YES | | NULL | |
| paint | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
The Philippe solution but cleaner:
My subtraction data is: '2018-09-22T11:05:00.000Z'
import datetime
import pandas as pd
df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)
In 2019 you can use querySelector for that.
It's supported by most browsers (https://caniuse.com/#search=querySelector)
document.querySelector('body').appendChild(i);
MySQL Utilities by Oracle have a command called mysqldiskusage that displays the disk usage of every database: https://dev.mysql.com/doc/mysql-utilities/1.6/en/mysqldiskusage.html
Without punctuation (as @Burusothman has mentioned):
current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;
O/P:
20170115072120
With punctuation:
current_date_time="`date "+%Y-%m-%d %H:%M:%S"`";
echo $current_date_time;
O/P:
2017-01-15 07:25:33
Yes, there are negative effects from this:
If you script out a change blocked by this flag you get something like the script below (all i am turning the ID column in Contact into an autonumbered IDENTITY column, but the table has dependencies). Note potential errors that can occur while the following is running:
--
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
DROP CONSTRAINT fk_Contact_AddressType
GO
ALTER TABLE ref.ContactpointType SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
DROP CONSTRAINT fk_contact_profile
GO
ALTER TABLE raw.Profile SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE raw.Tmp_Contact
(
ContactID int NOT NULL IDENTITY (1, 1),
ProfileID int NOT NULL,
AddressType char(2) NOT NULL,
ContactText varchar(250) NULL
) ON [PRIMARY]
GO
ALTER TABLE raw.Tmp_Contact SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT raw.Tmp_Contact ON
GO
IF EXISTS(SELECT * FROM raw.Contact)
EXEC('INSERT INTO raw.Tmp_Contact (ContactID, ProfileID, AddressType, ContactText)
SELECT ContactID, ProfileID, AddressType, ContactText FROM raw.Contact WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT raw.Tmp_Contact OFF
GO
ALTER TABLE raw.PostalAddress
DROP CONSTRAINT fk_AddressProfile
GO
ALTER TABLE raw.MarketingFlag
DROP CONSTRAINT fk_marketingflag_contact
GO
ALTER TABLE raw.Phones
DROP CONSTRAINT fk_phones_contact
GO
DROP TABLE raw.Contact
GO
EXECUTE sp_rename N'raw.Tmp_Contact', N'Contact', 'OBJECT'
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
Idx_Contact_1 PRIMARY KEY CLUSTERED
(
ProfileID,
ContactID
)
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
Idx_Contact UNIQUE NONCLUSTERED
(
ProfileID,
ContactID
)
GO
CREATE NONCLUSTERED INDEX idx_Contact_0 ON raw.Contact
(
AddressType
)
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
fk_contact_profile FOREIGN KEY
(
ProfileID
) REFERENCES raw.Profile
(
ProfileID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
fk_Contact_AddressType FOREIGN KEY
(
AddressType
) REFERENCES ref.ContactpointType
(
ContactPointTypeCode
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Phones ADD CONSTRAINT
fk_phones_contact FOREIGN KEY
(
ProfileID,
PhoneID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.Phones SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.MarketingFlag ADD CONSTRAINT
fk_marketingflag_contact FOREIGN KEY
(
ProfileID,
ContactID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.MarketingFlag SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.PostalAddress ADD CONSTRAINT
fk_AddressProfile FOREIGN KEY
(
ProfileID,
AddressID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.PostalAddress SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.
Update:
As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile
to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile
on OS X now requires the output to be a socket and the code won't work!
The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.
#include <fcntl.h>
#include <unistd.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <copyfile.h>
#else
#include <sys/sendfile.h>
#endif
int OSCopyFile(const char* source, const char* destination)
{
int input, output;
if ((input = open(source, O_RDONLY)) == -1)
{
return -1;
}
if ((output = creat(destination, 0660)) == -1)
{
close(input);
return -1;
}
//Here we use kernel-space copying for performance reasons
#if defined(__APPLE__) || defined(__FreeBSD__)
//fcopyfile works on FreeBSD and OS X 10.5+
int result = fcopyfile(input, output, 0, COPYFILE_ALL);
#else
//sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
off_t bytesCopied = 0;
struct stat fileinfo = {0};
fstat(input, &fileinfo);
int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
#endif
close(input);
close(output);
return result;
}
EDIT: Replaced the opening of the destination with the call to creat()
as we want the flag O_TRUNC
to be specified. See comment below.
You can use apply
for this, and it's a bit neater:
import numpy as np
import pandas as pd
np.random.seed(1)
df = pd.DataFrame(np.random.randn(4,4)* 4 + 3)
0 1 2 3
0 9.497381 0.552974 0.887313 -1.291874
1 6.461631 -6.206155 9.979247 -0.044828
2 4.276156 2.002518 8.848432 -5.240563
3 1.710331 1.463783 7.535078 -1.399565
df.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))
0 1 2 3
0 0.515087 0.133967 -0.651699 0.135175
1 0.125241 -0.689446 0.348301 0.375188
2 -0.155414 0.310554 0.223925 -0.624812
3 -0.484913 0.244924 0.079473 0.114448
Also, it works nicely with groupby
, if you select the relevant columns:
df['grp'] = ['A', 'A', 'B', 'B']
0 1 2 3 grp
0 9.497381 0.552974 0.887313 -1.291874 A
1 6.461631 -6.206155 9.979247 -0.044828 A
2 4.276156 2.002518 8.848432 -5.240563 B
3 1.710331 1.463783 7.535078 -1.399565 B
df.groupby(['grp'])[[0,1,2,3]].apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))
0 1 2 3
0 0.5 0.5 -0.5 -0.5
1 -0.5 -0.5 0.5 0.5
2 0.5 0.5 0.5 -0.5
3 -0.5 -0.5 -0.5 0.5
I am joining the choir recommending that you skip the now long outdated classes Date
, Calendar
, SimpleDateFormat
and friends. In particular I would warn against using the deprecated methods and constructors of the Date
class, like the Date(String)
constructor you used. They were deprecated because they don’t work reliably across time zones, so don’t use them. And yes, most of the constructors and methods of that class are deprecated.
While at the time you asked the question, Joda-Time was (from all I know) a clearly better alternative, time has moved on again. Today Joda-Time is a largely finished project, and its developers recommend you use java.time
, the modern Java date and time API, instead. I will show you how.
ZonedDateTime localTime = ZonedDateTime.now(ZoneId.systemDefault());
// Convert Local Time to UTC
OffsetDateTime gmtTime
= localTime.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("Local:" + localTime.toString()
+ " --> UTC time:" + gmtTime.toString());
// Reverse Convert UTC Time to Local time
localTime = gmtTime.atZoneSameInstant(ZoneId.systemDefault());
System.out.println("Local Time " + localTime.toString());
For starters, note that not only is the code only half as long as yours, it is also clearer to read.
On my computer the code prints:
Local:2017-09-02T07:25:46.211+02:00[Europe/Berlin] --> UTC time:2017-09-02T05:25:46.211Z
Local Time 2017-09-02T07:25:46.211+02:00[Europe/Berlin]
I left out the milliseconds from the epoch. You can always get them from System.currentTimeMillis();
as in your question, and they are independent of time zone, so I didn’t find them intersting here.
I hesitatingly kept your variable name localTime
. I think it’s a good name. The modern API has a class called LocalTime
, so using that name, only not capitalized, for an object that hasn’t got type LocalTime
might confuse some (a LocalTime
doesn’t hold time zone information, which we need to keep here to be able to make the right conversion; it also only holds the time-of-day, not the date).
Your conversion from local time to UTC was incorrect and impossible
The outdated Date
class doesn’t hold any time zone information (you may say that internally it always uses UTC), so there is no such thing as converting a Date
from one time zone to another. When I just ran your code on my computer, the first line it printed, was:
Local:Sat Sep 02 07:25:45 CEST 2017,1504329945967 --> UTC time:Sat Sep 02 05:25:45 CEST 2017-1504322745000
07:25:45 CEST
is correct, of course. The correct UTC time would have been 05:25:45 UTC
, but it says CEST
again, which is incorrect.
Now you will never need the Date
class again, :-) but if you were ever going to, the must-read would be All about java.util.Date on Jon Skeet’s coding blog.
Question: Can I use the modern API with my Java version?
If using at least Java 6, you can.
The only hard rule where list
must be used is where you need to distribute pointers to elements of the container.
Unlike with vector
, you know that the memory of elements won't be reallocated. If it could be then you might have pointers to unused memory, which is at best a big no-no and at worst a SEGFAULT
.
(Technically a vector
of *_ptr
would also work but in that case you are emulating list
so that's just semantics.)
Other soft rules have to do with the possible performance issues of inserting elements into the middle of a container, whereupon list
would be preferable.
Same thing was happening to me after I installed Node.js. Node and npm was recognized in PowerShell and Command Prompt but not in VS Code. I fixed it by adding the Node.js install path to the system's environment PATH
variable. The node.js install path on my system was:
C:\Program Files\nodejs
Where I find the node.exe
that is needed. The user's PATH
variable already had the Node.js install path but for some reason VS Code needs the Node.js install path in the system's PATH
variables.
Windows 10 instructions:
The other answers were great but this is another way to fix it that worked for me without needing to install stuff, run as admin, or change the default settings.
<div class="leads-search-table">
<div class="row col-md-6 col-md-offset-2 custyle">
<table class="table custab bordered">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Parent ID</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>News</td>
<td>News Cate</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
<tr>
<td>2</td>
<td>Products</td>
<td>Main Products</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
<tr>
<td>3</td>
<td>Blogs</td>
<td>Parent Blogs</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
</table>
</div>
</div>
Css
.custab{
border: 1px solid #ccc;
margin: 5% 0;
transition: 0.5s;
background-color: #fff;
-webkit-border-radius:4px;
border-radius: 4px;
border-collapse: separate;
}
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
i agree with you about alternative solutions which you mentioned above
1. Use POST instead of GET;
2. Transform the List into a JSON string and pass it to the service.
and its true that you can't add List
to MultiValuedMap
because of its impl class MultivaluedMapImpl
have capability to accept String Key and String Value. which is shown in following figure
still you want to do that things than try following code.
Controller Class
package net.yogesh.test;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import com.google.gson.Gson;
@Path("test")
public class TestController {
@Path("testMethod")
@GET
@Produces("application/text")
public String save(
@QueryParam("list") List<String> list) {
return new Gson().toJson(list) ;
}
}
Client Class
package net.yogesh.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class Client {
public static void main(String[] args) {
String op = doGet("http://localhost:8080/JerseyTest/rest/test/testMethod");
System.out.println(op);
}
private static String doGet(String url){
List<String> list = new ArrayList<String>();
list = Arrays.asList(new String[]{"string1,string2,string3"});
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
String lst = (list.toString()).substring(1, list.toString().length()-1);
params.add("list", lst);
ClientConfig config = new DefaultClientConfig();
com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
WebResource resource = client.resource(url);
ClientResponse response = resource.queryParams(params).type("application/x-www-form-urlencoded").get(ClientResponse.class);
String en = response.getEntity(String.class);
return en;
}
}
hope this'll help you.
It sounds like you're trying to link with your resulting object file with gcc
instead of g++
:
Note that programs using C++ object files must always be linked with g++, in order to supply the appropriate C++ libraries. Attempting to link a C++ object file with the C compiler gcc will cause "undefined reference" errors for C++ standard library functions:
$ g++ -Wall -c hello.cc
$ gcc hello.o (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
undefined reference to `__gxx_personality_v0'
Source: An Introduction to GCC - for the GNU compilers gcc and g++
Some of these examples are more complicated than you might need. To remove a single slash, from anywhere (leading or trailing), you could get away with something as simple as this:
let no_trailing_slash_url = site.replace('/', '');
Complete example:
let site1 = "www.somesite.com";
let site2 = "www.somesite.com/";
function someFunction(site)
{
let no_trailing_slash_url = site.replace('/', '');
return no_trailing_slash_url;
}
console.log(someFunction(site2)); // www.somesite.com
Note that .replace(...)
returns a string, it does not modify the string it is called on.
Try CSS:
<h2 style="color:#069">Process Report</h2>
If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:
<style type="text/css">
h2 {
color:#069;
}
</style>
if using logging.config.fileConfig with a configuration file use something like:
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
The stream editor does modify multiple files “inplace” when invoked with the -i
switch, which takes a backup file ending as argument. So
sed -i.bak 's/foo/bar/g' *
replaces foo
with bar
in all files in this folder, but does not descend into subfolders. This will however generate a new .bak
file for every file in your directory.
To do this recursively for all files in this directory and all its subdirectories, you need a helper, like find
, to traverse the directory tree.
find ./ -print0 | xargs -0 sed -i.bak 's/foo/bar/g' *
find
allows you further restrictions on what files to modify, by specifying further arguments like find ./ -name '*.php' -or -name '*.html' -print0
, if necessary.
Note: GNU sed
does not require a file ending, sed -i 's/foo/bar/g' *
will work, as well; FreeBSD sed
demands an extension, but allows a space in between, so sed -i .bak s/foo/bar/g *
works.
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});
We were seeing this same issue in one of our old projects that was targeting Framework 4.5.2. I tried several scenarios including all of the ones listed above: target 4.6.1, add System.ValueTuple package, delete bin, obj, and .vs folders. No dice. Repeat the same process for 4.7.2. Then tried removing the System.ValueTuple package since I was targeting 4.7.2 as one commenter suggested. Still nothing. Checked csproj file reference path. Looks right. Even dropped back down to 4.5.2 and installing the package again. All this with several VS restarts and deleting the same folders several times. Literally nothing worked.
I had to refactor to use a struct instead. I hope others don't continue to run into this issue in the future but thought this might be helpful if you end up as stumped up as we were.
Getting check status
var checked = $("#selectall").is(":checked");
Then for setting
$("input:checkbox").attr("checked",checked);
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
Since Maven 3.5.0 you can use the ${revision}
placeholder for that. The use is documented here: Maven CI Friendly Versions.
In short the parent pom looks like this (quoted from the Apache documentation):
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache</groupId>
<artifactId>apache</artifactId>
<version>18</version>
</parent>
<groupId>org.apache.maven.ci</groupId>
<artifactId>ci-parent</artifactId>
<name>First CI Friendly</name>
<version>${revision}</version>
...
<properties>
<revision>1.0.0-SNAPSHOT</revision>
</properties>
<modules>
<module>child1</module>
..
</modules>
</project>
and the child pom like this
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.maven.ci</groupId>
<artifactId>ci-parent</artifactId>
<version>${revision}</version>
</parent>
<groupId>org.apache.maven.ci</groupId>
<artifactId>ci-child</artifactId>
...
</project>
You also have to use the Flatten Maven Plugin to generate pom documents with the dedicated version number included for deployment. The HowTo is documented in the linked documentation.
Also @khmarbaise wrote a nice blob post about this feature: Maven: POM Files Without a Version in It?
You can try to install package version that does to exist. Then pip will list available versions
pip install hell==99999
ERROR: Could not find a version that satisfies the requirement hell==99999
(from versions: 0.1.0, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.3.0,
0.3.1, 0.3.2, 0.3.3, 0.3.4, 0.4.0, 0.4.1)
ERROR: No matching distribution found for hell==99999
If you don't want it using position fixed, and following you annoyingly on mobile, this seems to be working for me so far.
html {
min-height: 100%;
position: relative;
}
#site-footer {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 6px 2px;
background: #32383e;
}
Just set the html to min-height: 100%;
and position: relative;
, then position: absolute; bottom: 0; left: 0;
on the footer. I then made sure the footer was the last element in the body.
Let me know if this doesn't work for anyone else, and why. I know these tedious style hacks can behave strangely among various circumstances I'd not thought of.
I just had the same issue and this helped me:
html {
height: auto;
min-height: 100%;
background-size:cover;
}
if you use EclipseLink: You should be in a JPA transaction to access the Connection
entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();
I had this problem, after installing jdk7 next to Java 6. The binaries were correctly updated using update-alternatives --config java
to jdk7, but the $JAVA_HOME
environment variable still pointed to the old directory of Java 6.
Instead of rand()
, use newid()
, which is recalculated for each row in the result. The usual way is to use the modulo of the checksum. Note that checksum(newid())
can produce -2,147,483,648 and cause integer overflow on abs()
, so we need to use modulo on the checksum return value before converting it to absolute value.
UPDATE CattleProds
SET SheepTherapy = abs(checksum(NewId()) % 10000)
WHERE SheepTherapy IS NULL
This generates a random number between 0 and 9999.
Here are node and node-sass compatible versions list.
NodeJS Supported node-sass version *
Node 15 5.0+
Node 14 4.14+
Node 13 4.13+, < 5.0
Node 12 4.12+
Node 11 4.10+, < 5.0
Node 10 4.9+
Node 8 4.5.3+, < 5.0
Node < 8 < 5.0 < 57
If issue exists, upgrade or downgrade versions.
Use operator overloading feature of java
class Test {
void printType(String x) {
System.out.print("String");
}
void printType(int x) {
System.out.print("Int");
}
// same goes on with boolean,double,float,object ...
}
So, over SMTP when a message is submitted, the SMTP envelope (sender, recipients, etc.) is different from the actual data of the message.
The Sender
header is used to identify in the message who submitted it. This is usually the same as the From
header, which is who the message is from. However, it can differ in some cases where a mail agent is sending messages on behalf of someone else.
The Return-Path
header is used to indicate to the recipient (or receiving MTA) where non-delivery receipts are to be sent.
For example, take a server that allows users to send mail from a web page. So, [email protected]
types in a message and submits it. The server then sends the message to its recipient with From
set to [email protected]
. The actual SMTP submission uses different credentials, something like [email protected]
. So, the sender
header is set to [email protected]
, to indicate the From
header doesn't indicate who actually submitted the message.
In this case, if the message cannot be sent, it's probably better for the agent to receive the non-delivery report, and so Return-Path
would also be set to [email protected]
so that any delivery reports go to it instead of the sender.
If you are doing just that, a form submission to send e-mail, then this is probably a direct parallel with how you'd set the headers.
if (grid.selectedKeyNames().length > 0) {
$('#btnRemoveFromList').show();
} else {
$('#btnRemoveFromList').hide();
}
}
()
- calls the method
no parentheses - returns the property
temp = bankAccNos.contains(no) ? 1 : 2;
You could also use
$(this).prop('tagName');
if you're using jQuery 1.6 or higher.
you can use the following SQL statement to check the given column on table was indexed or not
select a.table_schema, a.table_name, a.column_name, index_name
from information_schema.columns a
join information_schema.tables b on a.table_schema = b.table_schema and
a.table_name = b.table_name and
b.table_type = 'BASE TABLE'
left join (
select concat(x.name, '/', y.name) full_path_schema, y.name index_name
FROM information_schema.INNODB_SYS_TABLES as x
JOIN information_schema.INNODB_SYS_INDEXES as y on x.TABLE_ID = y.TABLE_ID
WHERE x.name = 'your_schema'
and y.name = 'your_column') d on concat(a.table_schema, '/', a.table_name, '/', a.column_name) = d.full_path_schema
where a.table_schema = 'your_schema'
and a.column_name = 'your_column'
order by a.table_schema, a.table_name;
since the joins are against INNODB_SYS_*, so the match indexes only came from INNODB tables only
You don't need to use echo or grep. You could do this:
ping -oc 100000 8.8.8.8 > /dev/null && say "up" || say "down"
With the modification of a single line you could alter the fullcalendar.js script to allow a line break and put multiple information on the same line.
In FullCalendar.js on line ~3922 find htmlEscape(s) function and add .replace(/<br\s?/?>/g, '
') to the end of it.
function htmlEscape(s) {
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/\n/g, '<br />')
.replace(/<br\s?\/?>/g, '<br />');
}
This will allow you to have multiple lines for the title, separating the information. Example replace the event.title with title: 'All Day Event' + '<br />' + 'Other Description'
Well, you wouldn't call cURL directly, rather, you'd use one of the following options:
HttpWebRequest
/HttpWebResponse
WebClient
HttpClient
(available from .NET 4.5 on)I'd highly recommend using the HttpClient
class, as it's engineered to be much better (from a usability standpoint) than the former two.
In your case, you would do this:
using System.Net.Http;
var client = new HttpClient();
// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(new [] {
new KeyValuePair<string, string>("text", "This is a block of text"),
});
// Get the response.
HttpResponseMessage response = await client.PostAsync(
"http://api.repustate.com/v2/demokey/score.json",
requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}
Also note that the HttpClient
class has much better support for handling different response types, and better support for asynchronous operations (and the cancellation of them) over the previously mentioned options.
This works:
assertThat(list,IsEmptyCollection.empty())
The workaround is
(this will remove all the new lines and there should be whole one line)
now perform your replacements
search and replace thisismynewlineword to \r\n
(to undo the step 1)
If you don't want to add id's to your data, you could track by the index in the array, which will cause the items to be keyed by their position in the array instead of their value.
Like this:
var myArray = [1,1,1,1,1];
<li ng-repeat="item in myArray track by $index">
Use the following:
/**
* Utility method to replace the string from StringBuilder.
* @param sb the StringBuilder object.
* @param toReplace the String that should be replaced.
* @param replacement the String that has to be replaced by.
*
*/
public static void replaceString(StringBuilder sb,
String toReplace,
String replacement) {
int index = -1;
while ((index = sb.lastIndexOf(toReplace)) != -1) {
sb.replace(index, index + toReplace.length(), replacement);
}
}
I've had good luck with the SWF::File library on CPAN, and particularly the dumpswf.plx tool that comes with that distribution. It generates Perl code that, when run, regenerates your SWF.
To get the filenames, use:
var files = document.getElementById('inputElementID').files;
Using jQuery (since you already are) you can adapt this to the following:
$('input[type="file"][multiple]').change(
function(e){
var files = this.files;
for (i=0;i<files.length;i++){
console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
}
return false;
});
If you only have experience with imperative/OO languages, I suggest using a more conventional functional language as a stepping stone. Haskell is really different and you have to understand a lot of different concepts to get anywhere. I suggest tackling a ML-style language (like e.g. F#) first.
git submodule deinit --all -f
worked for me.
How would you expect recode to know that a file is Windows-1252? In theory, I believe any file is a valid Windows-1252 file, as it maps every possible byte to a character.
Now there are certainly characteristics which would strongly suggest that it's UTF-8 - if it starts with the UTF-8 BOM, for example - but they wouldn't be definitive.
One option would be to detect whether it's actually a completely valid UTF-8 file first, I suppose... again, that would only be suggestive.
I'm not familiar with the recode tool itself, but you might want to see whether it's capable of recoding a file from and to the same encoding - if you do this with an invalid file (i.e. one which contains invalid UTF-8 byte sequences) it may well convert the invalid sequences into question marks or something similar. At that point you could detect that a file is valid UTF-8 by recoding it to UTF-8 and seeing whether the input and output are identical.
Alternatively, do this programmatically rather than using the recode utility - it would be quite straightforward in C#, for example.
Just to reiterate though: all of this is heuristic. If you really don't know the encoding of a file, nothing is going to tell you it with 100% accuracy.
from r cookbook, where bp is your ggplot:
Remove legend for a particular aesthetic (fill):
bp + guides(fill=FALSE)
It can also be done when specifying the scale:
bp + scale_fill_discrete(guide=FALSE)
This removes all legends:
bp + theme(legend.position="none")
You really want to do this
flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))
This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).
I'm not a java expert but I solve your problem like this:
@FunctionalInterface
public interface AutoCompleteCallable<T> {
String call(T model) throws Exception;
}
I define the parameter in my special Interface
public <T> void initialize(List<T> entries, AutoCompleteCallable getSearchText) {.......
//call here
String value = getSearchText.call(item);
...
}
Finally, I implement getSearchText method while calling initialize method.
initialize(getMessageContactModelList(), new AutoCompleteCallable() {
@Override
public String call(Object model) throws Exception {
return "custom string" + ((xxxModel)model.getTitle());
}
})
For me, adding virtualenv (venv
)'s site-packages path to the paths of the interpreter works.
Finally!
using System.IO;
if (File.Exists(path))
{
Console.WriteLine("file exists");
}
If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.
at the command line
:\> cd <path you wish your server to reside>
:\> npm install connect
Then in a file (I named) Server.js
var connect = require('connect'),
http = require('http');
connect()
.use(connect.static('<pathyouwishtoserve>'))
.use(connect.directory('<pathyouwishtoserve>'))
.listen(8080);
Finally
:\>node Server.js
Caveats:
If you don't want to display the directory contents, exclude the .use(connect.directory line.
So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.
If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.
I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.
Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.
Commands I used (for better or worse):
Create a new file called node
:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$@"
sudo chmod -x /usr/local/bin/node
That ought to make
node Server.js
work just fine
TL;DR
npm uninstall node-sass
npm install [email protected]
Or, if using yarn (default in newer CRA versions)
yarn remove node-sass
yarn add [email protected]
Edit2: sass-loader v10.0.5 fixes it. Problem is, you might not be using it as a project dependency, but more as a dependency of your dependencies. CRA uses a fixed version, angular-cli locks to node-sass v4 an so on.
The recommendation for now is: if you're installing just node-sass check below workaround (and the note). If you're working on a blank project and you can manage your webpack configuration (not using CRA or a CLI to scaffold your project) install latest sass-loader.
Edit: this error comes from sass-loader. There is a semver mismatch since node-sass @latest is v5.0.0 and sass-loader expects ^4.0.0.
There is an open issue on their repository with an associated fix that needs to be reviewed. Until then, refer to the solution below.
Workaround: don't install node-sass 5.0.0 yet (major version was just bumped).
Uninstall node-sass
npm uninstall node-sass
Then install the latest version (before 5.0)
npm install [email protected]
Note: LibSass (hence node-sass as well) is deprecated and dart-sass is the recommended implementation. You can use sass
instead, which is a node distribution of dart-sass compiled to pure JavaScript.
Be warned though:
Be careful using this approach. React-scripts uses sass-loader v8, which prefers node-sass to sass (which has some syntax not supported by node-sass). If both are installed and the user worked with sass, this could lead to errors on css compilation
I think the solutions aren't correct 100% I would use ceil instead of floor, round will work but it isn't the right operation.
function dateDiff(str1, str2){
var diff = Date.parse(str2) - Date.parse(str1);
return isNaN(diff) ? NaN : {
diff: diff,
ms: Math.ceil(diff % 1000),
s: Math.ceil(diff / 1000 % 60),
m: Math.ceil(diff / 60000 % 60),
h: Math.ceil(diff / 3600000 % 24),
d: Math.ceil(diff / 86400000)
};
}
First off, it's not JSON: JSON mandates that all keys must be strings.
Secondly, regular arrays do what you want:
var Game = {
status: [
[
"val",
"val",
"val"
],
[
"val",
"val",
"val"
]
}
will work, if you use Game.status[0][0]
. You cannot use numbers with the dot notation (.0
).
Alternatively, you can quote the numbers (i.e. { "0": "val" }...
); you will have plain objects instead of Arrays, but the same syntax will work.
grid.newpage() ## If you're using ggplot
grid() ## If you just want to activate the device.
Use the quotemeta
function:
$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";
print "wee" if ($text_to_search =~ /$search_string/);
Quick and easy, add this to your page:
<style>
.select2-results {
max-height: 500px;
}
</style>
If your backend uses a secure connection ant you get using NSURLSession
CFNetwork SSLHandshake failed (-9801)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)
you need to check your server configuration especially to get ATS version and SSL certificate Info:
Instead of just Allowing Insecure Connection by setting NSExceptionAllowsInsecureHTTPLoads = YES
, instead you need to Allow Lowered Security in case your server do not meet the min requirement (v1.2) for ATS (or better to fix server side).
Allowing Lowered Security to a Single Server
<key>NSExceptionDomains</key>
<dict>
<key>api.yourDomaine.com</key>
<dict>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
use openssl client to investigate certificate and get your server configuration using openssl client :
openssl s_client -connect api.yourDomaine.com:port //(you may need to specify port or to try with https://... or www.)
..find at the end
SSL-Session:
Protocol : TLSv1
Cipher : AES256-SHA
Session-ID: //
Session-ID-ctx:
Master-Key: //
Key-Arg : None
Start Time: 1449693038
Timeout : 300 (sec)
Verify return code: 0 (ok)
App Transport Security (ATS) require Transport Layer Security (TLS) protocol version 1.2.
Requirements for Connecting Using ATS:
The requirements for a web service connection to use App Transport Security (ATS) involve the server, connection ciphers, and certificates, as follows:
Certificates must be signed with one of the following types of keys:
Secure Hash Algorithm 2 (SHA-2) key with a digest length of at least 256 (that is, SHA-256 or greater)
Elliptic-Curve Cryptography (ECC) key with a size of at least 256 bits
Rivest-Shamir-Adleman (RSA) key with a length of at least 2048 bits An invalid certificate results in a hard failure and no connection.
The following connection ciphers support forward secrecy (FS) and work with ATS:
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
Update: it turns out that openssl only provide the minimal protocol version Protocol : TLSv1 links
You simply have to use the filter
filter (see the documentation) :
<div id="totalPos">{{(tweets | filter:{polarity:'Positive'}).length}}</div>
<div id="totalNeut">{{(tweets | filter:{polarity:'Neutral'}).length}}</div>
<div id="totalNeg">{{(tweets | filter:{polarity:'Negative'}).length}}</div>
AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;
// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away
<div style="cursor: pointer;" onclick="theFunction()" onmouseover="this.style.background='red'" onmouseout="this.style.background=''" ><span>shanghai</span><span>male</span></div>
This will change the background color as well
Yes, it is true that Abstraction and Encapsulation are about hiding.
Using only relevant details and hiding unnecessary data at Design Level is called Abstraction. (Like selecting only relevant properties for a class 'Car' to make it more abstract or general.)
Encapsulation is the hiding of data at Implementation Level. Like how to actually hide data from direct/external access. This is done by binding data and methods to a single entity/unit to prevent external access. Thus, encapsulation is also known as data hiding at implementation level.
Add another div
or img
to your main div
and blur that instead. jsfiddle
.blur {
background:url('http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465') no-repeat center;
background-size:cover;
-webkit-filter: blur(13px);
-moz-filter: blur(13px);
-o-filter: blur(13px);
-ms-filter: blur(13px);
filter: blur(13px);
position:absolute;
width:100%;
height:100%;
}
You can include CSS styles in an html document with <style></style>
tags.
Example:
<style>
.myClass { background: #f00; }
.myOtherClass { font-size: 12px; }
</style>
See my blog post, Resize image in swift and objective C, for further details.
Image resize function in swift as below.
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
} else {
newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
Use the above function and resize image with 200*200 as below code
self.resizeImage(UIImage(named: "yourImageName")!, targetSize: CGSizeMake(200.0, 200.0))
swift3 updated
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
strAdd=strAdd.replace("&","'||'&'||'");
Using plain javascript:
element.parentNode
In jQuery:
element.parent()
testSpace.Style.Add("display", "none");
Delete the "target" folder under the offending module. Then Build | Rebuild Project. Also make sure your clear the web browsers cache.
I've seen 3 other fixes so far:
The solution boils down to clean up the .metadata folder with correct contents
Here is a simple program that displays the camera feed in a cv2.namedWindow
and will take a snapshot when you hit SPACE
. It will also quit if you hit ESC
.
import cv2
cam = cv2.VideoCapture(0)
cv2.namedWindow("test")
img_counter = 0
while True:
ret, frame = cam.read()
if not ret:
print("failed to grab frame")
break
cv2.imshow("test", frame)
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
elif k%256 == 32:
# SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()
I think this should answer your question for the most part. If there is any line of it that you don't understand let me know and I'll add comments.
If you need to grab multiple images per press of the SPACE
key, you will need an inner loop or perhaps just make a function that grabs a certain number of images.
Note that the key events are from the cv2.namedWindow
so it has to have focus.
That file will allow all crawlers access
User-agent: *
Allow: /
This basically allows all user agents (the *) to all parts of the site (the /).
Here is a one liner, to do it. You simply concatenate the two string in each of the column with a " " space in between.
Say df is your dataframe and columns are 'Time' and 'Date'. And your new column is DateAndTime.
df['DateAndTime'] = df['Date'].str.cat(df['Time'],sep=" ")
And if you also wanna handle entries like datetime objects, you can do this. You can tweak the formatting as per your needs.
df['DateAndTime'] = pd.to_datetime(df['DateAndTime'], format="%m/%d/%Y %I:%M:%S %p")
Cheers!! Happy Data Crunching.
Parent container has to have this:
position: relative;
Button itself has to have this:
position: relative;
bottom: 20px;
right: 20px;
or whatever you like
I agree with @Cthulhu answer. In your code you can reset your Scanner
object (in
).
in.reset();
This will reset your in object at the first line of your file.
There are two extensions you can use for this. This is added to react-native for setting these:
disableDevInDebug: true
: Disables dev server in debug buildTypebundleInDebug: true
: Adds jsbundle to debug buildType.So, your final project.ext.react
in android/app/build.gradle
should look like below
project.ext.react = [
enableHermes: false, // clean and rebuild if changing
devDisabledInDev: true, // Disable dev server in dev release
bundleInDev: true, // add bundle to dev apk
]
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null
to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
int val = '1' - '0';
This can be done using ascii codes where '0' is the lowest and the number characters count up from there
Sweet Jesus. I tried all of the above things (but found my settings identical). YET ANOTHER SOLUTION if you are having issues:
http://support.microsoft.com/kb/980368
Try installing this KB for your system. If you are seeing 404s it might be because you don't have this update -- and the isapi module just isn't getting found and there's not a lot you can do about that without this!
You write, "I know literally it's list of numbers and list of lists where all list contains only a number" but that's a bit of an unhelpful way to think about it.
The best way to think about NumPy arrays is that they consist of two parts, a data buffer which is just a block of raw elements, and a view which describes how to interpret the data buffer.
For example, if we create an array of 12 integers:
>>> a = numpy.arange(12)
>>> a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
Then a
consists of a data buffer, arranged something like this:
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
and a view which describes how to interpret the data:
>>> a.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> a.dtype
dtype('int64')
>>> a.itemsize
8
>>> a.strides
(8,)
>>> a.shape
(12,)
Here the shape (12,)
means the array is indexed by a single index which runs from 0 to 11. Conceptually, if we label this single index i
, the array a
looks like this:
i= 0 1 2 3 4 5 6 7 8 9 10 11
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
If we reshape an array, this doesn't change the data buffer. Instead, it creates a new view that describes a different way to interpret the data. So after:
>>> b = a.reshape((3, 4))
the array b
has the same data buffer as a
, but now it is indexed by two indices which run from 0 to 2 and 0 to 3 respectively. If we label the two indices i
and j
, the array b
looks like this:
i= 0 0 0 0 1 1 1 1 2 2 2 2
j= 0 1 2 3 0 1 2 3 0 1 2 3
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
which means that:
>>> b[2,1]
9
You can see that the second index changes quickly and the first index changes slowly. If you prefer this to be the other way round, you can specify the order
parameter:
>>> c = a.reshape((3, 4), order='F')
which results in an array indexed like this:
i= 0 1 2 0 1 2 0 1 2 0 1 2
j= 0 0 0 1 1 1 2 2 2 3 3 3
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
which means that:
>>> c[2,1]
5
It should now be clear what it means for an array to have a shape with one or more dimensions of size 1. After:
>>> d = a.reshape((12, 1))
the array d
is indexed by two indices, the first of which runs from 0 to 11, and the second index is always 0:
i= 0 1 2 3 4 5 6 7 8 9 10 11
j= 0 0 0 0 0 0 0 0 0 0 0 0
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
and so:
>>> d[10,0]
10
A dimension of length 1 is "free" (in some sense), so there's nothing stopping you from going to town:
>>> e = a.reshape((1, 2, 1, 6, 1))
giving an array indexed like this:
i= 0 0 0 0 0 0 0 0 0 0 0 0
j= 0 0 0 0 0 0 1 1 1 1 1 1
k= 0 0 0 0 0 0 0 0 0 0 0 0
l= 0 1 2 3 4 5 0 1 2 3 4 5
m= 0 0 0 0 0 0 0 0 0 0 0 0
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
and so:
>>> e[0,1,0,0,0]
6
See the NumPy internals documentation for more details about how arrays are implemented.
Since numpy.reshape
just creates a new view, you shouldn't be scared about using it whenever necessary. It's the right tool to use when you want to index an array in a different way.
However, in a long computation it's usually possible to arrange to construct arrays with the "right" shape in the first place, and so minimize the number of reshapes and transposes. But without seeing the actual context that led to the need for a reshape, it's hard to say what should be changed.
The example in your question is:
numpy.dot(M[:,0], numpy.ones((1, R)))
but this is not realistic. First, this expression:
M[:,0].sum()
computes the result more simply. Second, is there really something special about column 0? Perhaps what you actually need is:
M.sum(axis=0)
You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.
You could give the span a set width, then add the margin:0 auto
again. This would center-align it.
.left
{
background-color: #999999;
height: 50px;
width: 24.5%;
}
span.panelTitleTxt
{
display:block;
width:100px;
height: 100%;
margin: 0 auto;
}
The problem, as the error message suggests, is that you have constraints of type NSAutoresizingMaskLayoutConstraints
that conflict with your explicit constraints, because new_view.translatesAutoresizingMaskIntoConstraints
is set to true.
This is the default setting for views you create in code. You can turn it off like this:
var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100))
new_view.translatesAutoresizingMaskIntoConstraints = false
Also, your width and height constraints are weird. If you want the view to have a constant width, this is the proper way:
new_view.addConstraint(NSLayoutConstraint(
item:new_view, attribute:NSLayoutAttribute.Width,
relatedBy:NSLayoutRelation.Equal,
toItem:nil, attribute:NSLayoutAttribute.NotAnAttribute,
multiplier:0, constant:100))
(Replace 100 by the width you want it to have.)
If your deployment target is iOS 9.0 or later, you can use this shorter code:
new_view.widthAnchor.constraintEqualToConstant(100).active = true
Anyway, for a layout like this (fixed size and centered in parent view), it would be simpler to use the autoresizing mask and let the system translate the mask into constraints:
var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100))
new_view.backgroundColor = UIColor.redColor();
view.addSubview(new_view);
// This is the default setting but be explicit anyway...
new_view.translatesAutoresizingMaskIntoConstraints = true
new_view.autoresizingMask = [ .FlexibleTopMargin, .FlexibleBottomMargin,
.FlexibleLeftMargin, .FlexibleRightMargin ]
new_view.center = CGPointMake(view.bounds.midX, view.bounds.midY)
Note that using autoresizing is perfectly legitimate even when you're also using autolayout. (UIKit still uses autoresizing in lots of places internally.) The problem is that it's difficult to apply additional constraints to a view that is using autoresizing.
You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.
$('#musics').on('change', '#want',function(e) {
$(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
var ans=$(this).val();
console.log(($('#want').is(':checked')));
});
@{var listItems = new List<ListItem>
{
new ListItem { Text = "Exemplo1", Value="Exemplo1" },
new ListItem { Text = "Exemplo2", Value="Exemplo2" },
new ListItem { Text = "Exemplo3", Value="Exemplo3" }
};
}
@Html.DropDownList("Exemplo",new SelectList(listItems,"Value","Text"))
To hide the keyboard when activity starts.. write the following code in onCreate()..
InputMethodManager imm = (InputMethodManager)
getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
To clear focus and remove cursor from edittext.....
editText.clearFocus();
editText.setCursorVisible(false);
Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.
It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.
It has NOTHING to do with XML or JSON serialization.
Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.
Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.
I found another solution for this problem. This looks like another bug in WebKit (or probably Chrome), but it works. All you need to do - is to add a WebKit CSS Mask to the #wrapper element. You can use a single pixel png image and even include it to the CSS to save a HTTP request.
#wrapper {
width: 300px; height: 300px;
border-radius: 100px;
overflow: hidden;
position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */
/* this fixes the overflow:hidden in Chrome */
-webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
}
#box {
width: 300px; height: 300px;
background-color: #cde;
}?
globalThis is the future.
First, TypeScript files have two kinds of scopes
If your file hasn't any import
or export
line, this file would be executed in global scope that all declaration in it are visible outside this file.
So we would create global variables like this:
// xx.d.ts
declare var age: number
// or
// xx.ts
// with or without declare keyword
var age: number
// other.ts
globalThis.age = 18 // no error
All magic come from
var
. Replacevar
withlet
orconst
won't work.
If your file has any import
or export
line, this file would be executed within its own scope that we need to extend global by declaration-merging.
// xx[.d].ts
declare global {
var age: number;
}
// other.ts
globalThis.age = 18 // no error
You can see more about module in official docs
Some great answers above, using that info here is what I did today to solve the same issue:
$to_array = explode(',', $to);
foreach($to_array as $address)
{
$mail->addAddress($address, 'Web Enquiry');
}
You need to load it from resource stream.
Bitmap bmp = new Bitmap(
System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceStream("MyProject.Resources.myimage.png"));
If you want to know all resource names in your assembly, go with:
string[] all = System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceNames();
foreach (string one in all) {
MessageBox.Show(one);
}
Using AppCompatAcitivty
you can use just by
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
View logo = getLayoutInflater().inflate(R.layout.custom_toolbar, null);
mToolbar.addView(logo, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mToolbar.setContentInsetsAbsolute(0,0);
I know an answer has already been accepted, but wanted to point a few things out.
Setting the content-type
and charset
is obviously a good practice, doing it on the server is much better, because it ensures consistency across your application.
However, I would use UTF-8
only when the language of my application uses a lot of characters that are available only in the UTF-8
charset. If you want to show a unicode character or symbol in one of cases, you can do so without changing the charset
of your page.
HTML
renderers have always been able to display symbols which are not part of the encoding character set of the page, as long as you mention the symbol in its numeric character reference (NCR)
. Sounds weird but its true.
So, even if your html
has a header that states it has an encoding of ansi
or any of the iso
charsets, you can display a check mark by using its html character reference, in decimal - ✓ or in hex - ✓
So its a little difficult to understand why you are facing this issue on your pages. Can you check if the NCR value is correct, this is a good reference http://www.fileformat.info/info/unicode/char/2713/index.htm
The following may not be the best method--it is O(n^2). However, it should serve to get the job done (eventually).
count_of_elements_so_far = 0;
for (each element in linked list)
{
search for current element in first <count_of_elements_so_far>
if found, then you have a loop
else,count_of_elements_so_far++;
}
It turns out I didn't have Microsoft visual c++ installed, installing it solved the problem for me.
You can always make simple xsd schema for 'packages.config' to get rid of this warning. To do this, create file named "packages.xsd":
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
targetNamespace="urn:packages" xmlns="urn:packages">
<xs:element name="packages">
<xs:complexType>
<xs:sequence>
<xs:element name="package" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" type="xs:string" use="required" />
<xs:attribute name="version" type="xs:string" use="required" />
<xs:attribute name="targetFramework" type="xs:string" use="optional" />
<xs:attribute name="allowedVersions" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Location of this file (two options)
packages.xsd
across multiple projects, move it to the Visual Studio Schemas folder (the path may slightly differ, it's D:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas
for me).Then, edit <packages>
tag in packages.config
file (add xmlns
attribute):
<packages xmlns="urn:packages">
Now the warning should disappear (even if packages.config file is open in Visual Studio).
Note that the ::first-letter
selector does not work with inline elements, so it must be either block
or inline-block
, as follows:
.m_title {display:inline-block}
.m_title:first-letter {text-transform: uppercase}
On the server where Jenkins is running, I used
sudo setfacl -m user:tomcat:rw /var/run/docker.sock
And then run each docker container with
-v /var/run/docker.sock:/var/run/docker.sock
Using setfacl seems a better option, and no "-u user" is needed. The containers then run as the same user that is running Jenkins. But I would appreciate any feedback from the security experts.
As of Visual Studio Code Release 1.22 this comes free without the need of an extension.
Shift+Alt+O will take care of you.
Here is an example illustrating a closure in the Scheme programming language.
First we define a function defining a local variable, not visible outside the function.
; Function using a local variable
(define (function)
(define a 1)
(display a) ; prints 1, when calling (function)
)
(function) ; prints 1
(display a) ; fails: a undefined
Here is the same example, but now the function uses a global variable, defined outside the function.
; Function using a global variable
(define b 2)
(define (function)
(display b) ; prints 2, when calling (function)
)
(function) ; prints 2
(display 2) ; prints 2
And finally, here is an example of a function carrying its own closure:
; Function with closure
(define (outer)
(define c 3)
(define (inner)
(display c))
inner ; outer function returns the inner function as result
)
(define function (outer))
(function) ; prints 3
num=35; num.replace(3,'three'); =====> ERROR
num=35; num.toString().replace(3,'three'); =====> CORRECT !!!!!!
num='35'; num.replace(3,'three'); =====> CORRECT !!!!!!
I've used sortUsingFunction:: in some of my projects:
int SortPlays(id a, id b, void* context)
{
Play* p1 = a;
Play* p2 = b;
if (p1.score<p2.score)
return NSOrderedDescending;
else if (p1.score>p2.score)
return NSOrderedAscending;
return NSOrderedSame;
}
...
[validPlays sortUsingFunction:SortPlays context:nil];
Here is full java example:-
public class QuoteInJava {
public static void main (String args[])
{
System.out.println ("If you need to 'quote' in Java");
System.out.println ("you can use single \' or double \" quote");
}
}
Here is Out PUT:-
If you need to 'quote' in Java
you can use single ' or double " quote