I tried the old-fashioned version, of just adjusting aria-* and CSS attributes like many of these older answers, but eventually gave up and just did a conditional fake-click. Works a beaut':
HTML:
<a href="#" onclick="expandAll();"
title="Expand All" alt="Expand All"><img
src="/images/expand-all-icon.png"/></a>
<a href="#" onclick="collapseAll();"
title="Collapse All" alt="Collapse All"><img
src="/images/collapse-all-icon.png"/></a>
Javascript:
async function expandAll() {
let heads = $(".ui-accordion-header");
heads.each((index, el) => {
if ($(el).hasClass("ui-accordion-header-collapsed") === true)
$(el).trigger("click");
});
}
async function collapseAll() {
let heads = $(".ui-accordion-header");
heads.each((index, el) => {
if ($(el).hasClass("ui-accordion-header-collapsed") === false)
$(el).trigger("click");
});
}
(The HTML newlines are placed in those weird places to prevent whitespace in the presentation.)
Yes. IE7+ supports attribute selectors:
input[type=radio]
input[type^=ra]
input[type*=d]
input[type$=io]
Element input with attribute type which contains a value that is equal to, begins with, contains or ends with a certain value.
Other safe (IE7+) selectors are:
p > span { font-weight: bold; }
span ~ span { color: blue; }
Which for <p><span/><span/></p>
would effectively give you:
<p>
<span style="font-weight: bold;">
<span style="font-weight: bold; color: blue;">
</p>
Further reading: Browser CSS compatibility on quirksmode.com
I'm surprised that everyone else thinks it can't be done. CSS attribute selectors have been here for some time already. I guess it's time we clean up our .css files.
Change it to:
<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>
Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.
The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:
<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>
Oh and just for completeness, you should really prefer classes to direct CSS styles.
This is the best way, I know of to create dynamic variables in python.
my_dict = {}
x = "Buffalo"
my_dict[x] = 4
I found a similar, but not the same question here Creating dynamically named variables from user input
You should use DecimalFormat("0.#")
For 4.3000
Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
output is:
4.3
In case of 5.000 we have
Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
And the output is:
5
If it is hibernate and JPA. check your referred table name and columns might be a mismatch
I use it:
$firstDate = date( 'Y-m-d', strtotime( 'Last Monday', strtotime('-1 week') ));
$lastDate = date( 'Y-m-d', strtotime( 'First Sunday', strtotime('-1 week') ));
Hope this help you!
Very close! In your select
expression, you have to use a pipe (|
) before contains
.
This filter produces the expected output.
. - map(select(.Names[] | contains ("data"))) | .[] .Id
The jq Cookbook has an example of the syntax.
Filter objects based on the contents of a key
E.g., I only want objects whose genre key contains "house".
$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]' $ echo "$json" | jq -c '.[] | select(.genre | contains("house"))' {"genre":"deep house"} {"genre":"progressive house"}
Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.
The simplest way is to wrap the whole expression in an array constructor:
$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]
You can also use the map function:
$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]
map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f)
is equivalent to [.[]|f]
.
A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.
Another method utilizing the dplyr package:
library(dplyr)
df <- mtcars %>%
filter(mpg > 25)
Without the chain (%>%) operator:
library(dplyr)
df <- filter(mtcars, mpg > 25)
when
gem install overcommit
is run also this error have been placed in terminal.
Failed to build gem native extension
please do the same
xcode-select --install
and it will fix that issue too
Some things are possible, but not all, say for example you want line breaks, instead of using <br />
use %0D%0A
Example:
<a href="mailto:?subject=&body=Hello,%0D%0A%0D%0AHere is the link to the PDF Brochure.%0D%0A%0D%0ATo view the brochure please click the following link: http://www.uyslist.com/yachts/brochure.pdf"><img src="images/email.png" alt="EMail PDF Brochure" /></a>
Another more recent and object style way to do it :
$date = new DateTime('now');
$date->add(new DateInterval('P7D'));
Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".
You can achieve roughly the same effect by saying:
var displayName = user.name || "Anonymous";
Interesting question - I don't think there's any Oracle function that does this (almost like a "which" command in Unix), but you can get the resolution order for the name by:
select * from
(
select object_name objname, object_type, 'my object' details, 1 resolveOrder
from user_objects
where object_type not like 'SYNONYM'
union all
select synonym_name obj , 'my synonym', table_owner||'.'||table_name, 2 resolveOrder
from user_synonyms
union all
select synonym_name obj , 'public synonym', table_owner||'.'||table_name, 3 resolveOrder
from all_synonyms where owner = 'PUBLIC'
)
where objname like upper('&objOfInterest')
Here is my solution:
function getWeekDates(){
var day_milliseconds = 24*60*60*1000;
var dates = [];
var current_date = new Date();
var monday = new Date(current_date.getTime()-(current_date.getDay()-1)*day_milliseconds);
var sunday = new Date(monday.getTime()+6*day_milliseconds);
dates.push(monday);
for(var i = 1; i < 6; i++){
dates.push(new Date(monday.getTime()+i*day_milliseconds));
}
dates.push(sunday);
return dates;
}
Now you can pick date by returned array index.
Go to Task->Generate Scripts...
In Advanced in "Types of data for script" select "Schema and data"
and try to run this script in your lower version.
Visual Studio
If you are creating a setup project with VS, you can create a custom action who called a .NET method to start the service. But, it is not really recommended to use managed custom action in a MSI. See this page.
ServiceController controller = new ServiceController();
controller.MachineName = "";//The machine where the service is installed;
controller.ServiceName = "";//The name of your service installed in Windows Services;
controller.Start();
InstallShield or Wise
If you are using InstallShield or Wise, these applications provide the option to start the service. Per example with Wise, you have to add a service control action. In this action, you specify if you want to start or stop the service.
Wix
Using Wix you need to add the following xml code under the component of your service. For more information about that, you can check this page.
<ServiceInstall
Id="ServiceInstaller"
Type="ownProcess"
Vital="yes"
Name=""
DisplayName=""
Description=""
Start="auto"
Account="LocalSystem"
ErrorControl="ignore"
Interactive="no">
<ServiceDependency Id="????"/> ///Add any dependancy to your service
</ServiceInstall>
You can activate the modal without writing any JavaScript simply via data attributes.
The option "show" set to true shows the modal when initialized:
<div class="modal fade" tabindex="-1" role="dialog" data-show="true"></div>
The approach with istringstream can be improved in order to check that no other characters have been inserted after the expected argument:
#include <sstream>
int main(int argc, char *argv[])
{
if (argc >= 2)
{
std::istringstream iss( argv[1] );
int val;
if ((iss >> val) && iss.eof()) // Check eofbit
{
// Conversion successful
}
}
return 0;
}
You need to re-add that certificate to your machine or chose another certificate.
To choose another certificate or to recreate one, head over to the Project's properties page, click on Signing tab and either
Once either of these is done, you should be able to build it again.
The MaterialModule
was deprecated in the beta3 version with the goal that developers should only import into their applications what they are going to use and thus improve the bundle size.
The developers have now 2 options:
MyMaterialModule
which imports/exports the components that your application requires and can be imported by other (feature) modules in your application.Take the following as example (extracted from material page)
First approach:
import {MdButtonModule, MdCheckboxModule} from '@angular/material';
@NgModule({
imports: [MdButtonModule, MdCheckboxModule],
exports: [MdButtonModule, MdCheckboxModule],
})
export class MyOwnCustomMaterialModule { }
Then you can import this module into any of yours.
Second approach:
import {MdButtonModule, MdCheckboxModule} from '@angular/material';
@NgModule({
...
imports: [MdButtonModule, MdCheckboxModule],
...
})
export class PizzaPartyAppModule { }
Now you can use the respective material components in all the components declared in PizzaPartyAppModule
It is worth mentioning the following:
BrowserAnimationsModule
into your main module if you want the
animations to work@angular/cdk
to their package.json
(material dependency)BrowserModule
, as stated by the docs: Whichever approach you use, be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules.
I found that I can do some basic logic by running something like:
A=true
B=true
if ($A && $B); then
C=true
else
C=false
fi
echo $C
$(document).ready(function() {
$('#someButton').click(function() {
var names = [];
$('#MyDiv input:checked').each(function() {
names.push(this.name);
});
// now names contains all of the names of checked checkboxes
// do something with it
});
});
You can simply write :
class A(object):
def __init__(self):
print "Initialiser A was called"
class B(A):
def __init__(self):
A.__init__(self)
# A.__init__(self,<parameters>) if you want to call with parameters
print "Initialiser B was called"
class C(B):
def __init__(self):
# A.__init__(self) # if you want to call most super class...
B.__init__(self)
print "Initialiser C was called"
For me android:gravity="center"
did the trick in the parent layout element.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="@+id/fullImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/fullImageView"
android:layout_gravity="center" />
</LinearLayout>
This should do the trick: choice /T 5 /N /D Y
Replace the 5 with the time in seconds you want to wait...
However, will it automatically remove these committed files from the repository?
No.
The 'best' recipe to do this is using git filter-branch
as written about here:
The man page for git-filter-branch contains comprehensive examples.
Note You'll be re-writing history. If you had published any revisions containing the accidentally added files, this could create trouble for users of those public branches. Inform them, or perhaps think about how badly you need to remove the files.
Note In the presence of tags, always use the --tag-name-filter cat
option to git filter-branch
. It never hurts and will save you the head-ache when you realize later taht you needed it
Nobody has mention this in. above answers so i am mentioning it.
This error can also come if you're in the wrong folder or path of your pem file is not correct. I was having similar issue and found that my pem file was not there from where i am executing the ssh command
cd KeyPair
ssh -i Keypair.pem [email protected]
Correct your Code like this:
try
{ //method try starts
String sql = "INSERT into TblName (col1, col2) VALUES(?, ?)";
pStmt = obj.getConnection().prepareStatement(sql);
pStmt.setLong(1, subscriberID);
for (String language : additionalLangs) {
pStmt.setInt(2, Integer.parseInt(language));
pStmt.execute();
}
} //method/try ends
finally
{ //finally starts
pStmt.close()
}
Are you sure, that you're really closing your pStatements, connections and results?
To analyze open objects you can implment a delegator pattern, which wraps code around your statemant, connection and result objects. So you'll see, if an object will successfully closed.
An Example for: pStmt = obj.getConnection().prepareStatement(sql);
class obj{
public Connection getConnection(){
return new ConnectionDelegator(...here create your connection object and put it into ...);
}
}
class ConnectionDelegator implements Connection{
Connection delegates;
public ConnectionDelegator(Connection con){
this.delegates = con;
}
public Statement prepareStatement(String sql){
return delegates.prepareStatement(sql);
}
public void close(){
try{
delegates.close();
}finally{
log.debug(delegates.toString() + " was closed");
}
}
}
We can use FlexBox for Sticky Footer and Header without using POSITIONS in CSS.
.container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
height: 50px;_x000D_
flex-shrink: 0;_x000D_
background-color: #037cf5;_x000D_
}_x000D_
_x000D_
footer {_x000D_
height: 50px;_x000D_
flex-shrink: 0;_x000D_
background-color: #134c7d;_x000D_
}_x000D_
_x000D_
main {_x000D_
flex: 1 0 auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<header>HEADER</header>_x000D_
<main class="content">_x000D_
_x000D_
</main>_x000D_
<footer>FOOTER</footer>_x000D_
</div>
_x000D_
DEMO - JSFiddle
Note : Check browser supports for FlexBox. caniuse
As hanry has mentioned above putting liner iterpolator is fine. But if rotation is inside a set you must put android:shareInterpolator="false" to make it smooth.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
**android:shareInterpolator="false"**
>
<rotate
android:interpolator="@android:anim/linear_interpolator"
android:duration="300"
android:fillAfter="true"
android:repeatCount="10"
android:repeatMode="restart"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%" />
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:duration="3000"
android:fillAfter="true"
android:pivotX="50%"
android:pivotY="50%"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="0"
android:toYScale="0" />
</set>
If Sharedinterpolator being not false, the above code gives glitches.
Seems to me that:
df1 = df[df['col1']==some_value] WILL NOT create a new DataFrame, basically, changes in df1 will be reflected in the parent df. This leads to the warning. Whereas, df1 = df[df['col1]]==some_value].copy() WILL create a new DataFrame, and changes in df1 will not be reflected in df. the copy() method is recommended if you don't want to make changes to your original df.
If you give the label an ID, like this:
<label for="foo" id="foo_label">
Then this would work:
#foo_label { display: none;}
Your other options aren't really cross-browser friendly, unless javascript is an option. The CSS3 selector, not as widely supported looks like this:
[for="foo"] { display: none;}
A really simple way to use argparse and amend the '-h'/ '--help' switches to display your own personal code help instructions is to set the default help to False, you can also add as many additional .add_arguments as you like:
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.parse_args()
Run: python test.py -h
Output:
usage: test.py [-h]
optional arguments:
-h, --help To run this script please provide two arguments
StringValues
is an array of strings. You can get your string value by providing an index, e.g. HttpContext.Request.Query["page"][0]
.
Reached the same problem, but instead of "hacking" or emulating command line:
Found this answer here.
from paramiko import SSHClient
from scp import SCPClient
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')
with SCPClient(ssh.get_transport()) as scp:
scp.put('test.txt', 'test2.txt')
scp.get('test2.txt')
This may also happen if you have a slash before the folder name:
path = '/folder1/folder2'
OSError: [Errno 13] Permission denied: '/folder1'
comes up with an error but this one works fine:
path = 'folder1/folder2'
I have met the similiar issue. I would link to run Ant task fron Maven build and I got the issue. I have fixed it as bellow steps:
And it worked for me.
For me, the reason for this error was that there was a folder with the same name as the python module I was trying to import.
|-- core <-- empty directory on the same level as the module that throws the error
|-- core.py
And python treated that folder as a python package and tried to import from that empty package "core", not from core.py.
Seems like for some reason git left that empty folder during the branches switch
So I just removed that folder and everything worked like a charm
I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh
let's use imshow
:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]) # added some commas and array creation code
fig = plt.figure(figsize=(6, 3.2))
ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')
cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
In my case I wanted to center my logo on a website when the browser has 800px
or less, then I did this by using the @media
tag:
@media screen and (max-width: 800px) {
#logo {
float: none;
margin: 0;
text-align: center;
display: block;
width: auto;
}
}
It worked for me, hope somebody find this solution useful. :) For more information see this.
DataFrame.to_dict()
converts DataFrame to dictionary.
Example
>>> df = pd.DataFrame(
{'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b'])
>>> df
col1 col2
a 1 0.1
b 2 0.2
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}
See this Documentation for details
If you have MySQL version >= 5.7, then you can try this:
SELECT JSON_EXTRACT(name, "$.id") AS name
FROM table
WHERE JSON_EXTRACT(name, "$.id") > 3
Output:
+-------------------------------+
| name |
+-------------------------------+
| {"id": "4", "name": "Betty"} |
+-------------------------------+
Please check MySQL reference manual for more details:
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html
instead of body
type a list of elements you want.
I realized following line was missing in settings.gradle file
include ':app'
make sure you include ":app" module
jQuery Dropdown Check List can be used to transform a regular multiple select html element into a dropdown checkbox list, it works on client so can be used with any server side technology:
(source: googlecode.com)
If you're not able to use NewChart.js you just need to change the way to set the color using array instead. Find the helper iteration inside Chart.js:
Replace this line:
fillColor : dataset.fillColor,
For this one:
fillColor : dataset.fillColor[index],
The resulting code:
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets,function(dataset,datasetIndex){
var datasetObject = {
label : dataset.label || null,
fillColor : dataset.fillColor,
strokeColor : dataset.strokeColor,
bars : []
};
this.datasets.push(datasetObject);
helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.bars.push(new this.BarClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.strokeColor,
//Replace this -> fillColor : dataset.fillColor,
// Whith the following:
fillColor : dataset.fillColor[index],
highlightFill : dataset.highlightFill || dataset.fillColor,
highlightStroke : dataset.highlightStroke || dataset.strokeColor
}));
},this);
},this);
And in your js:
datasets: [
{
label: "My First dataset",
fillColor: ["rgba(205,64,64,0.5)", "rgba(220,220,220,0.5)", "rgba(24,178,235,0.5)", "rgba(220,220,220,0.5)"],
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [2000, 1500, 1750, 50]
}
]
You need to use double apostrophe instead of single in the "You''re", eg:
String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);
Update the master branch, which you need to do regardless.
Then, one of:
Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.
Merge your branch into master, and resolve the merge conflicts.
Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.
None of these is better than the other, they just have different trade-off patterns.
I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.
To rebase and keep the branch you would:
git checkout <branch> && git rebase <target>
In your case, check out the old branch, then
git rebase master
to get it rebuilt against master.
Strace is a tool that tells you how your application interacts with your operating system.
It does this by telling you what OS system calls your application uses and with what parameters it calls them.
So for instance you see what files your program tries to open, and weather the call succeeds.
You can debug all sorts of problems with this tool. For instance if application says that it cannot find library that you know you have installed you strace would tell you where the application is looking for that file.
And that is just a tip of the iceberg.
Sometimes something strange happens and using Visual Studio to automatically restore doesn't work. In that case you can use the NuGet Package Manager Console. That is opened within Visual Studio from Tools -> NuGet Package Manager -> Package Manager Console. The commands within the console are simple. And to get context help while typing a command just press the button and it will give you all options that start with the letters you're typing. So if a package isn't installed, for example log4net, type the following command:
Install-Package log4net
You can do a whole lot more, like specify the version to install, update a package, uninstall a package, etc.
I had to use the console to help me when Visual Studio was acting like a weirdo.
Try this for allowing only 2 decimal in input type
<input type="number" step="0.01" class="form-control" />
Or Use jQuery as suggested by @SamohtVII
$( "#ELEMENTID" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
outgoing url in mvc generated based on the current routing schema.
because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.
to solve this problem you should use UrlParameter.Optional:
<a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
same browsers may return string for border width, in this parseInt will return NaN so make sure you parse value to int properly.
var getInt = function (string) {
if (typeof string == "undefined" || string == "")
return 0;
var tempInt = parseInt(string);
if (!(tempInt <= 0 || tempInt > 0))
return 0;
return tempInt;
}
var liWidth = $(this).width();
liWidth += getInt($(this).css("padding-left"));
liWidth += getInt($(this).css("padding-right"));
liWidth += getInt($(this).css("border-left-width"));
liWidth += getInt($(this).css("border-right-width"));
Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:
// All code to find the files are here and is working perfectly...
It doesn't make sense to call a API Controller from another controller on the same website.
This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...
You can.
package test;
public class Test {
public static void main(String[] args) {
B b = new B();
}
}
class B {
// Essentially package-private - cannot be accessed anywhere else but inside the `test` package
}
Try:
for word in words:
if word[0] == word[-1]:
c += 1
print c
for word in words
returns the items of words
, not the index. If you need the index sometime, try using enumerate
:
for idx, word in enumerate(words):
print idx, word
would output
0, 'aba'
1, 'xyz'
etc.
The -1
in word[-1]
above is Python's way of saying "the last element". word[-2]
would give you the second last element, and so on.
You can also use a generator to achieve this.
c = sum(1 for word in words if word[0] == word[-1])
If you want to keep the history, showing the commit and the revert, you should use:
git revert GIT_COMMIT_HASH
enter the message explaining why are you reverting and then:
git push
When you issue git log
you'll see both the "wrong" commit and revert log messages.
According to the documentation on here http://angularjs.blogspot.co.uk/2017/03/angular-400-now-available.html you 'should' just be able to run...
npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save
I tried it and got a couple of errors due to my zone.js and ngrx/store libraries being older versions.
Updating those to the latest versions npm install zone.js@latest --save
and npm install @ngrx/store@latest -save
, then running the angular install again worked for me.
According to RFC 4337 § 2, video/mp4
is indeed the correct Content-Type for MPEG-4 video.
Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.
You could try updating the table to get rid of these characters:
UPDATE dbo.[audit]
SET UserID = REPLACE(UserID, CHAR(0), '')
WHERE CHARINDEX(CHAR(0), UserID) > 0;
But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
FROM dbo.[audit];
But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:
ALTER TABLE dbo.[audit]
ADD CONSTRAINT do_not_allow_stupid_data
CHECK (CHARINDEX(CHAR(0), UserID) = 0);
EDIT
Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:
DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;
-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;
-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;
Please confirm that this code on its own (well, the first SELECT
, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:
SELECT UserID, CONVERT(VARBINARY(32), UserID)
FROM dbo.[audit]
WHERE UserID LIKE '%[^0-9]%';
So take a random row, and then paste the output into a query like this:
DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
SET @i = @i + 1;
END
This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0)
- since you can't really filter out the rows that contain CHAR(0)
because they could contain CHAR(0)
and CHAR(something else)
. For all we know you have values in the table like:
SELECT '15' + CHAR(9) + '23' + CHAR(0);
...which also can't be converted to an integer, whether you've replaced CHAR(0)
or not.
I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.
I had to edit the C:\Windows\System32\inetsrv\config\applicationHost.config
file and add <requestLimits maxAllowedContentLength="1073741824" />
to the end of the...
<configuration>
<system.webServer>
<security>
<requestFiltering>
section.
This caught me out because someone had changed the "Run" configuration's "Build Configuration" setting to "Release" (under "Product" > "Edit Scheme.." > "Run *.app").
This is normally set to "Debug" and hence it was NOT using the developer certificate and provisioning profile that I was expecting, it was using the distribution certificates instead.
In addition to this I found that if you look in the Console Log for the device (via Organiser), there may be an error code that better indicates your problem. For example I had...
Mon Sep 5 09:39:56 unknown installd[304] <Error>: profile not valid: 0xe8008012
I then googled "0xe8008012" and got the following page which indicates a "0xE8008012 - The UUID of the device does not match any in the Provisioning Profile being loaded" error.
I had problems correctly displaying some symbols with regular download as pdf. So downloaded as tex jupyter nbconvert --to latex "my notebook.ipynb"
, made some tweaks with notepad (as an example, in my case I needed these lines for my language
\usepackage{tgpagella}
\usepackage[lithuanian,english]{babel}
) and then exported to pdf with latex --output-format=pdf "my notebook.tex"
.
But finally, however, to retain the same characters as you see in a browser I ended up using my Chrome browser printing: Ctrl+P
Print to pdf
. It adds unnecessary header and footer but everything else remains as it is. No more errors processing tqdm progress bar, no more code going out of the page and so on. Simple as that.
Try to restart the server and launch it back using npm start
Try the following:
java -cp jar1:jar2:jar3:dir1:. HelloWorld
The default classpath (unless there is a CLASSPATH environment variable) is the current directory so if you redefine it, make sure you're adding the current directory (.) to the classpath as I have done.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Call java script function on Code behind</title>
<script type="text/javascript">
function abc()
{
var a=20;
var b=30;
alert("you enter"+a+":"+b);
}
</script>
</head>
cs code
protected void Page_Load(object sender, EventArgs e)
{
TextBox2.Attributes.Add("onkeypress", "return abc();");
}
try this
Rather than kludging it so you can continue, why not back up and wonder why you're running into a NaN in the first place?
If any of the numeric inputs to an operation is NaN, the output will also be NaN. That's the way the current IEEE Floating Point standard works (it's not just Javascript). That behavior is for a good reason: the underlying intention is to keep you from using a bogus result without realizing it's bogus.
The way NaN works is if something goes wrong way down in some sub-sub-sub-operation (producing a NaN at that lower level), the final result will also be NaN, which you'll immediately recognize as an error even if your error handling logic (throw/catch maybe?) isn't yet complete.
NaN as the result of an arithmetic calculation always indicates something has gone awry in the details of the arithmetic. It's a way for the computer to say "debugging needed here". Rather than finding some way to continue anyway with some number that's hardly ever right (is 0 really what you want?), why not find the problem and fix it.
A common problem in Javascript is that both parseInt(...)
and parseFloat(...)
will return NaN if given a nonsensical argument (null
, ''
, etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.)
Perhaps for ease of coding you want a function to retrieve a value from the user, clean it up, and provide a default value if necessary, like this:
function getFoobarFromUser(elementid) {
var foobar = parseFloat(document.getElementById(elementid).innerHTML)
if (isNaN(foobar)) foobar = 3.21; // default value
return(foobar.toFixed(2));
}
// Instead Of
var index = arr.indexOf(200)
// Use
var index = arr.includes(200);
Please Note: Includes function is a simple instance method on the array and helps to easily find if an item is in the array(including NaN unlike indexOf)
If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.
The following is a decent solution across Unix/Linux installations, that does not rely on any unusual program features. This supports a multi-line message body, multiple attachments, and all the other typical features of mailx
.
Unfortunately, it does not fit on a single line.
#!/bin/ksh
# Get the date stamp for temporary files
DT_STAMP=`date +'%C%y%m%d%H%M%S'`
# Create a multi-line body
echo "here you put the message body
which can be split across multiple lines!
woohoo!
" > body-${DT_STAMP}.mail
# Add several attachments
uuencode File1.pdf File1.pdf > attachments-${DT_STAMP}.mail
uuencode File2.pdf File2.pdf >> attachments-${DT_STAMP}.mail
# Put everything together and send it off!
cat body-${DT_STAMP}.mail attachments-${DT_STAMP}.mail > out-${DT_STAMP}.mail
mailx -s "here you put the message subject" [email protected] < out-${DT_STAMP}.mail
# Clean up temporary files
rm body-${DT_STAMP}.mail
rm attachments-${DT_STAMP}.mail
rm out-${DT_STAMP}.mail
This still loops through the cartesian product of the two lists, but it does it one line:
>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False
This also have the advantage that any
short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings
in linesX
. If you want to find multiple occurrences you could do something like this:
>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]
If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.
From https://developer.mozilla.org/en-US/docs/Web/CSS/background-color
To set background color:
/* Hexadecimal value with color and 100% transparency*/
background-color: #11ffee00; /* Fully transparent */
/* Special keyword values */
background-color: transparent;
/* HSL value with color and 100% transparency*/
background-color: hsla(50, 33%, 25%, 1.00); /* 100% transparent */
/* RGB value with color and 100% transparency*/
background-color: rgba(117, 190, 218, 1.0); /* 100% transparent */
To represent the character you can use Universal Character Names (UCNs). The character '?' has the Unicode value U+0444 and so in C++ you could write it '\u0444' or '\U00000444'. Also if the source code encoding supports this character then you can just write it literally in your source code.
// both of these assume that the character can be represented with
// a single char in the execution encoding
char b = '\u0444';
char a = '?'; // this line additionally assumes that the source character encoding supports this character
Printing such characters out depends on what you're printing to. If you're printing to a Unix terminal emulator, the terminal emulator is using an encoding that supports this character, and that encoding matches the compiler's execution encoding, then you can do the following:
#include <iostream>
int main() {
std::cout << "Hello, ? or \u0444!\n";
}
This program does not require that '?' can be represented in a single char. On OS X and most any modern Linux install this will work just fine, because the source, execution, and console encodings will all be UTF-8 (which supports all Unicode characters).
Things are harder with Windows and there are different possibilities with different tradeoffs.
Probably the best, if you don't need portable code (you'll be using wchar_t, which should really be avoided on every other platform), is to set the mode of the output file handle to take only UTF-16 data.
#include <iostream>
#include <io.h>
#include <fcntl.h>
int main() {
_setmode(_fileno(stdout), _O_U16TEXT);
std::wcout << L"Hello, \u0444!\n";
}
Portable code is more difficult.
```
if (Get-Module -ListAvailable -Name <<MODULE_NAME>>) {
Write-Verbose -Message "<<MODULE_NAME>> Module does not exist." -Verbose
}
if (!(Get-Module -Name <<MODULE_NAME>>)) {
Get-Module -ListAvailable <<MODULE_NAME>> | Import-Module | Out-Null
}
```
This is a FAQ:
//someName[3]
means: all someName
elements in the document, that are the third someName
child of their parent -- there may be many such elements.
What you want is exactly the 3rd someName
element:
(//someName)[3]
Explanation: the []
has a higher precedence (priority) than //
. Remember always to put expressions of the type //someName
in brackets when you need to specify the Nth node of their selected node-list.
The quick and dirty way, you can view the available environment variables from the below link.
http://localhost:8080/env-vars.html/
Just replace localhost
with your Jenkins hostname, if its different
How about this: https://commons.apache.org/proper/commons-jcs/ (updated to new address, as JCS is now in Apache Commons)
Couldn't believe that there is not one single correct answer here. No need to allocate pointers, and the unmultiplied values still need to be normalized. To cut to the chase, here is the correct version for Swift 4. For UIImage
just use .cgImage
.
extension CGImage {
func colors(at: [CGPoint]) -> [UIColor]? {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo),
let ptr = context.data?.assumingMemoryBound(to: UInt8.self) else {
return nil
}
context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height))
return at.map { p in
let i = bytesPerRow * Int(p.y) + bytesPerPixel * Int(p.x)
let a = CGFloat(ptr[i + 3]) / 255.0
let r = (CGFloat(ptr[i]) / a) / 255.0
let g = (CGFloat(ptr[i + 1]) / a) / 255.0
let b = (CGFloat(ptr[i + 2]) / a) / 255.0
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
}
The reason you have to draw/convert the image first into a buffer is because images can have several different formats. This step is required to convert it to a consistent format you can read.
A map will not keep insertion order. Use *(myMap.begin())
to get the value of the first pair (the one with the smallest key when ordered).
You could also do myMap.begin()->first
to get the key and myMap.begin()->second
to get the value.
Alternative solution:
>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29
As an alternative to the default title
attribute tooltips, you can make your own custom CSS tooltips using :before
/:after
pseudo elements and HTML5 data-*
attributes.
Using the provided CSS, you can add a tooltip to an element using the data-tooltip
attribute.
You can also control the position of the custom tooltip using the data-tooltip-position
attribute (accepted values: top
/right
/bottom
/left
).
For instance, the following will add a tooltop positioned at the bottom of the span element.
<span data-tooltip="Custom tooltip text." data-tooltip-position="bottom">Custom bottom tooltip.</span>
You can display the custom tooltips with pseudo elements by retrieving the custom attribute values using the attr()
function.
[data-tooltip]:before {
content: attr(data-tooltip);
}
In terms of positioning the tooltip, just use the attribute selector and change the placement based on the attribute's value.
Full CSS used in the example - customize this to your needs.
[data-tooltip] {
display: inline-block;
position: relative;
cursor: help;
padding: 4px;
}
/* Tooltip styling */
[data-tooltip]:before {
content: attr(data-tooltip);
display: none;
position: absolute;
background: #000;
color: #fff;
padding: 4px 8px;
font-size: 14px;
line-height: 1.4;
min-width: 100px;
text-align: center;
border-radius: 4px;
}
/* Dynamic horizontal centering */
[data-tooltip-position="top"]:before,
[data-tooltip-position="bottom"]:before {
left: 50%;
-ms-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
}
/* Dynamic vertical centering */
[data-tooltip-position="right"]:before,
[data-tooltip-position="left"]:before {
top: 50%;
-ms-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
[data-tooltip-position="top"]:before {
bottom: 100%;
margin-bottom: 6px;
}
[data-tooltip-position="right"]:before {
left: 100%;
margin-left: 6px;
}
[data-tooltip-position="bottom"]:before {
top: 100%;
margin-top: 6px;
}
[data-tooltip-position="left"]:before {
right: 100%;
margin-right: 6px;
}
/* Tooltip arrow styling/placement */
[data-tooltip]:after {
content: '';
display: none;
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
/* Dynamic horizontal centering for the tooltip */
[data-tooltip-position="top"]:after,
[data-tooltip-position="bottom"]:after {
left: 50%;
margin-left: -6px;
}
/* Dynamic vertical centering for the tooltip */
[data-tooltip-position="right"]:after,
[data-tooltip-position="left"]:after {
top: 50%;
margin-top: -6px;
}
[data-tooltip-position="top"]:after {
bottom: 100%;
border-width: 6px 6px 0;
border-top-color: #000;
}
[data-tooltip-position="right"]:after {
left: 100%;
border-width: 6px 6px 6px 0;
border-right-color: #000;
}
[data-tooltip-position="bottom"]:after {
top: 100%;
border-width: 0 6px 6px;
border-bottom-color: #000;
}
[data-tooltip-position="left"]:after {
right: 100%;
border-width: 6px 0 6px 6px;
border-left-color: #000;
}
/* Show the tooltip when hovering */
[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
display: block;
z-index: 50;
}
If you have a jenkinsfile for your pipeline, check if you see at execution time your branch name in your environment variables.
You can print them with:
pipeline {
agent any
environment {
DISABLE_AUTH = 'true'
DB_ENGINE = 'sqlite'
}
stages {
stage('Build') {
steps {
sh 'printenv'
}
}
}
}
However, PR 91 shows that the branch name is only set in certain pipeline configurations:
I agree with everyone else here: With JS on the client, the cat is out of the bag and there is nothing completely foolproof that can be done.
Having said that; in some cases I do this to put some hurdles in the way of those who want to take a look at the code. This is how the algorithm works (roughly)
The server creates 3 hashed and salted values. One for the current timestamp, and the other two for each of the next 2 seconds. These values are sent over to the client via Ajax to the client as a comma delimited string; from my PHP module. In some cases, I think you can hard-bake these values into a script section of HTML when the page is formed, and delete that script tag once the use of the hashes is over The server is CORS protected and does all the usual SERVER_NAME etc check (which is not much of a protection but at least provides some modicum of resistance to script kiddies).
Also it would be nice, if the the server checks if there was indeed an authenticated user's client doing this
The client then sends the same 3 hashed values back to the server thru an ajax call to fetch the actual JS that I need. The server checks the hashes against the current time stamp there... The three values ensure that the data is being sent within the 3 second window to account for latency between the browser and the server
The server needs to be convinced that one of the hashes is matched correctly; and if so it would send over the crucial JS back to the client. This is a simple, crude "One time use Password" without the need for any database at the back end.
This means, that any hacker has only the 3 second window period since the generation of the first set of hashes to get to the actual JS code.
The entire client code can be inside an IIFE function so some of the variables inside the client are even more harder to read from the Inspector console
This is not any deep solution: A determined hacker can register, get an account and then ask the server to generate the first three hashes; by doing tricks to go around Ajax and CORS; and then make the client perform the second call to get to the actual code -- but it is a reasonable amount of work.
Moreover, if the Salt used by the server is based on the login credentials; the server may be able to detect who is that user who tried to retreive the sensitive JS (The server needs to do some more additional work regarding the behaviour of the user AFTER the sensitive JS was retreived, and block the person if the person, say for example, did not do some other activity which was expected)
An old, crude version of this was done for a hackathon here: http://planwithin.com/demo/tadr.html That wil not work in case the server detects too much latency, and it goes beyond the 3 second window period
Here is a simple solution using a dynamically generated style sheet served up by the same server as the iframe content. Quite simply the style sheet "knows" what is in the iframe, and knows the dimensions to use to style the iframe. This gets around the same origin policy restrictions.
http://www.8degrees.co.nz/2010/06/09/dynamically-resize-an-iframe-depending-on-its-content/
So the supplied iframe code would have an accompanying style sheet like so...
<link href="http://your.site/path/to/css?contents_id=1234&dom_id=iframe_widget" rel="stylesheet" type="text/css" />?
<iframe id="iframe_widget" src="http://your.site/path/to/content?content_id=1234" frameborder="0" width="100%" scrolling="no"></iframe>
This does require the server side logic being able to calculate the dimensions of the rendered content of the iframe.
ANSI encoding is a slightly generic term used to refer to the standard code page on a system, usually Windows. It is more properly referred to as Windows-1252 on Western/U.S. systems. (It can represent certain other Windows code pages on other systems.) This is essentially an extension of the ASCII character set in that it includes all the ASCII characters with an additional 128 character codes. This difference is due to the fact that "ANSI" encoding is 8-bit rather than 7-bit as ASCII is (ASCII is almost always encoded nowadays as 8-bit bytes with the MSB set to 0). See the article for an explanation of why this encoding is usually referred to as ANSI.
The name "ANSI" is a misnomer, since it doesn't correspond to any actual ANSI standard, but the name has stuck. ANSI is not the same as UTF-8.
I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.
The information schema isn't the place to treat these things (see DDL database commands).
When you add a comment you need to change the table structure (table comments).
From MySQL 5.6 documentation:
INFORMATION_SCHEMA is a database within each MySQL instance, the place that stores information about all the other databases that the MySQL server maintains. The INFORMATION_SCHEMA database contains several read-only tables. They are actually views, not base tables, so there are no files associated with them, and you cannot set triggers on them. Also, there is no database directory with that name.
Although you can select INFORMATION_SCHEMA as the default database with a USE statement, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE operations on them.
The linked comment is incorrect : 'L' to '1' will produce a rising edge.
In addition, if your clock signal transitions from 'H' to '1', rising_edge(clk)
will (correctly) not trigger while (clk'event and clk = '1')
(incorrectly) will.
Granted, that may look like a contrived example, but I have seen clock waveforms do that in real hardware, due to failures elsewhere.
Sample Code: To set Footer text programatically
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = grdTotal.ToString("c");
}
}
UPDATED CODE:
decimal sumFooterValue = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string sponsorBonus = ((Label)e.Row.FindControl("Label2")).Text;
string pairingBonus = ((Label)e.Row.FindControl("Label3")).Text;
string staticBonus = ((Label)e.Row.FindControl("Label4")).Text;
string leftBonus = ((Label)e.Row.FindControl("Label5")).Text;
string rightBonus = ((Label)e.Row.FindControl("Label6")).Text;
decimal totalvalue = Convert.ToDecimal(sponsorBonus) + Convert.ToDecimal(pairingBonus) + Convert.ToDecimal(staticBonus) + Convert.ToDecimal(leftBonus) + Convert.ToDecimal(rightBonus);
e.Row.Cells[6].Text = totalvalue.ToString();
sumFooterValue += totalvalue;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = sumFooterValue.ToString();
}
}
In .aspx Page
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowFooter="True"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:TemplateField HeaderText="Report Date" SortExpression="reportDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("reportDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("reportDate", "{0:dd MMMM yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sponsor Bonus" SortExpression="sponsorBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("sponsorBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("sponsorBonus", "{0:0.00}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pairing Bonus" SortExpression="pairingBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("pairingBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("pairingBonus", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Static Bonus" SortExpression="staticBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Left Bonus" SortExpression="leftBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Right Bonus" SortExpression="rightBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" SortExpression="total">
<EditItemTemplate>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
My Blog - Asp.net Gridview Article
This is a quick crafty way of doing it, and also a way to pick a custom size.
I go here:
http://vimeo.com/api/v2/video/[VIDEO ID].php
Download the file, open it, and find the 640 pixels wide thumbnail, it will have a format like so:
https://i.vimeocdn.com/video/[LONG NUMBER HERE]_640.jpg
You take the link, change the 640 for - for example - 1400, and you end up with something like this:
https://i.vimeocdn.com/video/[LONG NUMBER HERE]_1400.jpg
Paste it on your browser search bar and enjoy.
Cheers,
If you don't mind open source, you could use the subbuffer and subparser classes from https://github.com/EdgeCast/json_parser. The original string is left intact, there is no allocation and no copying of data. I have not compiled the following so there may be errors.
std::string input_string("hello world");
subbuffer input(input_string);
subparser flds(input, ' ', subparser::SKIP_EMPTY);
while (!flds.empty())
{
subbuffer fld = flds.next();
// do something with fld
}
// or if you know it is only two fields
subbuffer fld1 = input.before(' ');
subbuffer fld2 = input.sub(fld1.length() + 1).ltrim(' ');
Installing Subversion for Windows should solve the issue. Please see my answer here - https://stackoverflow.com/a/31627732/3433133
This function creates a temporary form, then send data using jQuery :
function postToIframe(data,url,target){
$('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
$.each(data,function(n,v){
$('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
});
$('#postToIframe').submit().remove();
}
target is the 'name' attr of the target iFrame, and data is a JS object :
data={last_name:'Smith',first_name:'John'}
This is a derivite of previous post, but this gets the latest version of the .net framework 4 in my tests.
get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL"
Which will allow you to invoke-command to remote machine:
invoke-command -computername server01 -scriptblock {get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL" | select pscomputername,version,release}
Which sets up this possibility with ADModule and naming convention prefix:
get-adcomputer -Filter 'name -like "*prefix*"' | % {invoke-command -computername $_.name -scriptblock {get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL" | select pscomputername,version,release} | ft
Use -A and -B switches (mean lines-after and lines-before):
grep -A 1 -B 1 FAILED file.txt
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
The answer to your question is that you need to have permissions. Type the following code in your manifest.xml file:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_OWNER_DATA"></uses-permission>
<uses-permission android:name="android.permission.READ_OWNER_DATA"></uses-permission>`
It worked for me...
You can also use the subset function:
data <- subset(data, select=c(3,2,1))
You should better use the [] operator as in the other answers, but it may be useful to know that you can do a subset and a column reorder operation in a single command.
Update:
You can also use the select function from the dplyr package:
data = data %>% select(Time, out, In, Files)
I am not sure about the efficiency, but thanks to dplyr's syntax this solution should be more flexible, specially if you have a lot of columns. For example, the following will reorder the columns of the mtcars dataset in the opposite order:
mtcars %>% select(carb:mpg)
And the following will reorder only some columns, and discard others:
mtcars %>% select(mpg:disp, hp, wt, gear:qsec, starts_with('carb'))
Read more about dplyr's select syntax.
You should be able to use non-greedy quantifiers, specifically *?. You're going to probably want the following:
Pattern MY_PATTERN = Pattern.compile("\\[(.*?)\\]");
This will give you a pattern that will match your string and put the text within the square brackets in the first group. Have a look at the Pattern API Documentation for more information.
To extract the string, you could use something like the following:
Matcher m = MY_PATTERN.matcher("FOO[BAR]");
while (m.find()) {
String s = m.group(1);
// s now contains "BAR"
}
Late answer but might be useful useful for someone else
If neither DBCC ShrinkDatabase/ShrinkFile or SSMS (Tasks/Shrink/Database) doesn’t help, there are tools from Quest and ApexSQL that can get the job done, and even schedule periodic shrinking if you need it.
I’ve used the latter one in free trial to do this some time ago, by following short description at the end of this article:
All you need to do is install ApexSQL Backup, click "Shrink database" button in the main ribbon, select database in the window that will pop-up, and click "Finish".
You have a class on your CSS that is overwriting your width and height, the class reads as such:
.postItem img {
height: auto;
width: 450px;
}
Remove that and your width/height properties on the img
tag should work.
Even more simple, pass the $event
object to ng-click
to access the event properties. As an example:
<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>
Within your clickEvent() = function(obj) {}
function you can access the data
value like this:
var dataValue = obj.target.attributes.data.value;
Which would return exampleData
.
Here's a full jsFiddle.
This is really ugly but it works, text is tested on registry:2.5.1. I did not manage to get delete working smoothly even after updating configuration to enable delete. The ID was really difficult to retrieve, had to login to get it, maybe some misunderstanding. Anyway, the following works:
Login to the container
docker exec -it registry sh
Define variables matching your container and container version:
export NAME="google/cadvisor"
export VERSION="v0.24.1"
Move to the the registry directory:
cd /var/lib/registry/docker/registry/v2
Delete files related to your hash:
find . | grep `ls ./repositories/$NAME/_manifests/tags/$VERSION/index/sha256`| xargs rm -rf $1
Delete manifests:
rm -rf ./repositories/$NAME/_manifests/tags/$VERSION
Logout
exit
Run the GC:
docker exec -it registry bin/registry garbage-collect /etc/docker/registry/config.yml
If all was done properly some information about deleted blobs is shown.
You need to use JavaScript in your HTML and make sure you are using forms so that. You may finally serialize the data using Ajax method to push the data from HTML into database
If you want efficiency and simplicity, I recommend this approach:
function Palindrome(str) {
let len = str.length,
i = 0;
if (len < 3)
return false;
while (len--) {
if (str[i] === str[len])
i++;
else
return false;
}
return true;
}
console.log(Palindrome('aba'))//true
console.log(Palindrome('abc'))//false
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
Looking at the question, ftell
can easily get the number of bytes.
long size = ftell(FILENAME);
printf("total size is %ld bytes",size);
OpenProcess Function
From MSDN:
To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege.
Use prop()
for updating the hidden property, and change()
for handling the change event.
$('#check').change(function() {_x000D_
$("#delete").prop("hidden", !this.checked);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr>_x000D_
<td>_x000D_
<input id="check" type="checkbox" name="del_attachment_id[]" value="<?php echo $attachment['link'];?>">_x000D_
</td>_x000D_
_x000D_
<td id="delete" hidden="true">_x000D_
the file will be deleted from the newsletter_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
I would be using laravel whereDoesntHave to achieve this.
Customer::whereDoesntHave('orders')->get();
If you can get access from a Windows machine, you can use xcopy with /T and /E to copy just the folder structure (the /E includes empty folders)
[EDIT!]
This one uses rsync to recreate the directory structure but without the files. http://psung.blogspot.com/2008/05/copying-directory-trees-with-rsync.html
Might actually be better :)
$data = array(
'name' => $_POST['name'] ,
'groupname' => $_POST['groupname'],
'age' => $_POST['age']
);
$this->db->where('id', $_POST['id']);
$this->db->update('tbl_user', $data);
Once you write the c# code and save it. You can use the command prompt to execute it just like the other code.
In command prompt you enter the directory your file is in and type
To Compile:
mcs yourfilename.cs
To Execute:
mono yourfilename.exe
if you want your .exe file to be different with a different name, type
To Compile:
mcs yourfilename.cs -out:anyname.exe
To Execute:
mono anyname.exe
This should help!
Alternatively, you can use jinfo
jinfo -flags <vmid>
jinfo -sysprops <vmid>
It seems that you dont have any problem with the environmental variables.
Compile your file from src with
javac a/A.java
Then, run your program as
java a.A
Auto PY to EXE - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.
py2exe is probably what you want, but it only works on Windows.
PyInstaller works on Windows and Linux.
Py2app works on the Mac.
You could write a function that converts a scientific notation to regular, something like
def sc2std(x):
s = str(x)
if 'e' in s:
num,ex = s.split('e')
if '-' in num:
negprefix = '-'
else:
negprefix = ''
num = num.replace('-','')
if '.' in num:
dotlocation = num.index('.')
else:
dotlocation = len(num)
newdotlocation = dotlocation + int(ex)
num = num.replace('.','')
if (newdotlocation < 1):
return negprefix+'0.'+'0'*(-newdotlocation)+num
if (newdotlocation > len(num)):
return negprefix+ num + '0'*(newdotlocation - len(num))+'.0'
return negprefix + num[:newdotlocation] + '.' + num[newdotlocation:]
else:
return s
If the index is not sorted, you have to iterate through the array at least once to find the highest value. I'd use a simple for
loop:
int? maxVal = null; //nullable so this works even if you have all super-low negatives
int index = -1;
for (int i = 0; i < anArray.Length; i++)
{
int thisNum = anArray[i];
if (!maxVal.HasValue || thisNum > maxVal.Value)
{
maxVal = thisNum;
index = i;
}
}
This is more verbose than something using LINQ or other one-line solutions, but it's probably a little faster. There's really no way to make this faster than O(N).
The --no-ff
option ensures that a fast forward merge will not happen, and that a new commit object will always be created. This can be desirable if you want git to maintain a history of feature branches.
In the above image, the left side is an example of the git history after using git merge --no-ff
and the right side is an example of using git merge
where an ff merge was possible.
EDIT: A previous version of this image indicated only a single parent for the merge commit. Merge commits have multiple parent commits which git uses to maintain a history of the "feature branch" and of the original branch. The multiple parent links are highlighted in green.
You've got the syntax all wrong:
cursor.execute ("""
UPDATE tblTableName
SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
For more, read the documentation.
One BIG difference to note is .Equals() will throw an exception if first string is null, Whereas == will not.
string s = null;
string a = "a";
//Throws {"Object reference not set to an instance of an object."}
if (s.Equals(a))
Console.WriteLine("s is equal to a");
//no Exception
if(s==a)
Console.WriteLine("s is equal to a");
SortedList decorator from Java Happy Libraries can be used to decorate TreeList from Apache Collections. That would produce a new list which performance is compareable to TreeSet. https://sourceforge.net/p/happy-guys/wiki/Sorted%20List/
Running assembly Code on Mac is just 3 steps away from you. It could be done using XCODE but better is to use NASM Command Line Tool. For My Ease I have already installed Xcode, if you have Xcode installed its good.
But You can do it without XCode as well.
Just Follow:
brew install nasm
nasm -f macho64 myFile.asm
ld -macosx_version_min 10.7.0 -lSystem -o OutPutFile myFile.o && ./64
Simple Text File named myFile.asm is written below for your convenience.
global start
section .text
start:
mov rax, 0x2000004 ; write
mov rdi, 1 ; stdout
mov rsi, msg
mov rdx, msg.len
syscall
mov rax, 0x2000001 ; exit
mov rdi, 0
syscall
section .data
msg: db "Assalam O Alaikum Dear", 10
.len: equ $ - msg
select
c.name as [column name],
t.name as [type name],
tbl.name as [table name]
from sys.columns c
inner join sys.types t
on c.system_type_id = t.system_type_id
inner join sys.tables tbl
on c.object_id = tbl.object_id
where
c.object_id = OBJECT_ID('YourTableName1')
and
t.name like '%YourSearchDataType%'
union
(select
c.name as [column name],
t.name as [type name],
tbl.name as [table name]
from sys.columns c
inner join sys.types t
on c.system_type_id = t.system_type_id
inner join sys.tables tbl
on c.object_id = tbl.object_id
where
c.object_id = OBJECT_ID('YourTableName2')
and
t.name like '%YourSearchDataType%')
union
(select
c.name as [column name],
t.name as [type name],
tbl.name as [table name]
from sys.columns c
inner join sys.types t
on c.system_type_id = t.system_type_id
inner join sys.tables tbl
on c.object_id = tbl.object_id
where
c.object_id = OBJECT_ID('YourTableName3')
and
t.name like '%YourSearchDataType%')
order by tbl.name
To search which column is in which table based on your search data type for three different table in one database. This query is expandable to 'n' tables.
Try to declare UseHttpGet over your method.
[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
return "Hello World";
}
In the end i came to the conclusion that without modifying how the query works i could not store the values in variables. I used SQL profiler to catch the values and then hard coded them into the query to see how it worked. There were 18 of these integer arrays and some had over 30 elements in them.
I think that there is a need for MS/SQL to introduce some aditional datatypes into the language. Arrays are quite common and i don't see why you couldn't use them in a stored proc.
Have a look at json_encode
(http://php.net/manual/en/function.json-encode.php). It is available as of PHP 5.2. Use the parameter dataType: 'json'
to have it parsed for you. You'll have the Object as the first argument in success then. For further information have a look at the jQuery-documentation: http://api.jquery.com/jQuery.ajax/
You can make a new file under [.git\refs\remotes\origin] with name "HEAD" and put content "ref: refs/remotes/origin/master" to it. This should solve your problem.
It seems that clone from an empty repos will lead to this. Maybe the empty repos do not have HEAD because no commit object exist.
You can use the
git log --remotes --branches --oneline --decorate
to see the difference between each repository, while the "problem" one do not have "origin/HEAD"
Edit: Give a way using command line
You can also use git command line to do this, they have the same result
git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master
To complement the existing helpful answers:
Using Bash's own regex-matching operator, =~
, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:
set -- '12-34-5678' # set $1 to sample value
kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match
Note, however, that the caveat re using flavor-specific regex constructs such as \d
equally applies:
While =~
supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.
To remain portable (in the context of Bash), stick to the POSIX ERE specification.
Note that =~
even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]}
array variable.
Further notes:
$kREGEX_DATE
is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).
While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \
.
\<
is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes
doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes
does.I've changed variable name REGEX_DATE
to kREGEX_DATE
(k
signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.
Hope this will help you...
RadioButton rb = (RadioButton) findViewById(R.id.yourFirstRadioButton);
rb.setOnClickListener(first_radio_listener);
and
OnClickListener first_radio_listener = new OnClickListener (){
public void onClick(View v) {
//Your Implementaions...
}
};
I've written something that detects if the page contains the anchor that was clicked on, and if not, goes to the normal page, otherwise it scrolls to the specific section:
$('a[href*=\\#]').on('click',function(e) {
var target = this.hash;
var $target = $(target);
console.log(targetname);
var targetname = target.slice(1, target.length);
if(document.getElementById(targetname) != null) {
e.preventDefault();
}
$('html, body').stop().animate({
'scrollTop': $target.offset().top-120 //or the height of your fixed navigation
}, 900, 'swing', function () {
window.location.hash = target;
});
});
Since Python 3.3, you can use the class ExitStack
from the contextlib
module.
It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
The canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
Here is a generic example:
from contextlib import ExitStack
class X:
num = 1
def __init__(self):
self.num = X.num
X.num += 1
def __repr__(self):
cls = type(self)
return '{cls.__name__}{self.num}'.format(cls=cls, self=self)
def __enter__(self):
print('enter {!r}'.format(self))
return self.num
def __exit__(self, exc_type, exc_value, traceback):
print('exit {!r}'.format(self))
return True
xs = [X() for _ in range(3)]
with ExitStack() as stack:
print(stack._exit_callbacks)
nums = [stack.enter_context(x) for x in xs]
print(stack._exit_callbacks)
print(stack._exit_callbacks)
print(nums)
Output:
deque([])
enter X1
enter X2
enter X3
deque([<function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f86158>, <function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f861e0>, <function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f86268>])
exit X3
exit X2
exit X1
deque([])
[1, 2, 3]
The bookmarks extension mentioned in the accepted answer conflicts with toggling breakpoints via the margin.
You could do the same with breakpoints and select the debug tab on the left to see them listed. Better yet, use File, Preferences, Keyboard Shortcuts and set (Shift+)Ctrl+F9 to navigate between them, even across files:
When you subtract two variables of type TIMESTAMP
, you get an INTERVAL DAY TO SECOND
which includes a number of milliseconds and/or microseconds depending on the platform. If the database is running on Windows, systimestamp
will generally have milliseconds. If the database is running on Unix, systimestamp
will generally have microseconds.
1 select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' )
2* from dual
SQL> /
SYSTIMESTAMP-TO_TIMESTAMP('2012-07-23','YYYY-MM-DD')
---------------------------------------------------------------------------
+000000000 14:51:04.339000000
You can use the EXTRACT
function to extract the individual elements of an INTERVAL DAY TO SECOND
SQL> ed
Wrote file afiedt.buf
1 select extract( day from diff ) days,
2 extract( hour from diff ) hours,
3 extract( minute from diff ) minutes,
4 extract( second from diff ) seconds
5 from (select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' ) diff
6* from dual)
SQL> /
DAYS HOURS MINUTES SECONDS
---------- ---------- ---------- ----------
0 14 55 37.936
You can then convert each of those components into milliseconds and add them up
SQL> ed
Wrote file afiedt.buf
1 select extract( day from diff )*24*60*60*1000 +
2 extract( hour from diff )*60*60*1000 +
3 extract( minute from diff )*60*1000 +
4 round(extract( second from diff )*1000) total_milliseconds
5 from (select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' ) diff
6* from dual)
SQL> /
TOTAL_MILLISECONDS
------------------
53831842
Normally, however, it is more useful to have either the INTERVAL DAY TO SECOND
representation or to have separate columns for hours, minutes, seconds, etc. rather than computing the total number of milliseconds between two TIMESTAMP
values.
There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!
Lazy loaded objects are subclasses
If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means thatthis.getClass() == o.getClass()
will return false
. For example:
Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy
If you're dealing with an ORM, using o instanceof Person
is the only thing that will behave correctly.
Lazy loaded objects have null-fields
ORMs usually use the getters to force loading of lazy loaded objects. This means that person.name
will be null
if person
is lazy loaded, even if person.getName()
forces loading and returns "John Doe". In my experience, this crops up more often in hashCode()
and equals()
.
If you're dealing with an ORM, make sure to always use getters, and never field references in hashCode()
and equals()
.
Saving an object will change its state
Persistent objects often use a id
field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in hashCode()
. But you can use it in equals()
.
A pattern I often use is
if (this.getId() == null) {
return this == other;
}
else {
return this.getId().equals(other.getId());
}
But: you cannot include getId()
in hashCode()
. If you do, when an object is persisted, its hashCode
changes. If the object is in a HashSet
, you'll "never" find it again.
In my Person
example, I probably would use getName()
for hashCode
and getId()
plus getName()
(just for paranoia) for equals()
. It's okay if there are some risk of "collisions" for hashCode()
, but never okay for equals()
.
hashCode()
should use the non-changing subset of properties from equals()
You can use reflections
return Class.forName(className).getConstructor(String.class).newInstance(arg);
Gradle's local repository folder is:
Defined dependencies will be loaded from remote repositories into gradle's local repository folder. For each loaded file, gradle will be create a new folder named with md5 value of the original file (pom,jar,..). Full path for the dependency file is made up from :
If our defined dependency is:
Then the library will be loaded into :
It changes the rules for override priority of css cascades. See the CSS2 spec.
Result Set
are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1)
only get you the data in first column of first row. In order to change to next row, you need to call next()
a quick example
while (rs.next()) {
String sid = rs.getString(1);
String lid = rs.getString(2);
// Do whatever you want to do with these 2 values
}
there are many useful method in ResultSet
, you should take a look :)
The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to:
var query = lst.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
If you want to know how many times the elements are repeated, you can use:
var query = lst.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => new { Element = y.Key, Counter = y.Count() })
.ToList();
This will return a List
of an anonymous type, and each element will have the properties Element
and Counter
, to retrieve the information you need.
And lastly, if it's a dictionary you are looking for, you can use
var query = lst.GroupBy(x => x)
.Where(g => g.Count() > 1)
.ToDictionary(x => x.Key, y => y.Count());
This will return a dictionary, with your element as key, and the number of times it's repeated as value.
You can use eclipse style of JavaDoc comment generation through "Fix doc comment". Open "Preference" -> "Keymap" and assign "Fix doc comment" action to a key that you want.
We create a validation set to
Why validation set used:
After giving necessary permissions in DCOM configurations I also needed to change the identity of my application in the IIS to a custom account
If you just want to add a string to it, the simple answer is:
ListBox.Items.Add("some text");
built on dmark's answer to get the following, which is useful if you want the equiv of sprintf and hopefully will help someone...
def sprint(object):
result = ''
for i in [v for v in dir(object) if not callable(getattr(object, v)) and v[0] != '_']:
result += '\n%s:' % i + str(getattr(object, i, ''))
return result
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
The only way I achieved the "best case" scenario described, was putting the image as a background:
<div class="container"></div>?
.container {
width: 150px;
height: 100px;
background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: 50% 50%;
}?
I had the same error when multiline string included new line (\n
) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.
Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n
) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.
I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.
Modify your log4j.properties
file accordingly:
log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog
Change the log levels for each logger depending to your needs.
From Bash Guide section on globbing
To use an extglob in a parameter expansion
#Turn on extended globbing
shopt -s extglob
#Trim leading and trailing whitespace from a variable
x=${x##+([[:space:]])}; x=${x%%+([[:space:]])}
#Turn off extended globbing
shopt -u extglob
Here's the same functionality wrapped in a function (NOTE: Need to quote input string passed to function):
trim() {
# Determine if 'extglob' is currently on.
local extglobWasOff=1
shopt extglob >/dev/null && extglobWasOff=0
(( extglobWasOff )) && shopt -s extglob # Turn 'extglob' on, if currently turned off.
# Trim leading and trailing whitespace
local var=$1
var=${var##+([[:space:]])}
var=${var%%+([[:space:]])}
(( extglobWasOff )) && shopt -u extglob # If 'extglob' was off before, turn it back off.
echo -n "$var" # Output trimmed string.
}
Usage:
string=" abc def ghi ";
#need to quote input-string to preserve internal white-space if any
trimmed=$(trim "$string");
echo "$trimmed";
If we alter the function to execute in a subshell, we don't have to worry about examining the current shell option for extglob, we can just set it without affecting the current shell. This simplifies the function tremendously. I also update the positional parameters "in place" so I don't even need a local variable
trim() {
shopt -s extglob
set -- "${1##+([[:space:]])}"
printf "%s" "${1%%+([[:space:]])}"
}
so:
$ s=$'\t\n \r\tfoo '
$ shopt -u extglob
$ shopt extglob
extglob off
$ printf ">%q<\n" "$s" "$(trim "$s")"
>$'\t\n \r\tfoo '<
>foo<
$ shopt extglob
extglob off
Probably AES. Blowfish was the direct predecessor to Twofish. Twofish was Bruce Schneier's entry into the competition that produced AES. It was judged as inferior to an entry named Rijndael, which was what became AES.
Interesting aside: at one point in the competition, all the entrants were asked to give their opinion of how the ciphers ranked. It's probably no surprise that each team picked its own entry as the best -- but every other team picked Rijndael as the second best.
That said, there are some basic differences in the basic goals of Blowfish vs. AES that can (arguably) favor Blowfish in terms of absolute security. In particular, Blowfish attempts to make a brute-force (key-exhaustion) attack difficult by making the initial key setup a fairly slow operation. For a normal user, this is of little consequence (it's still less than a millisecond) but if you're trying out millions of keys per second to break it, the difference is quite substantial.
In the end, I don't see that as a major advantage, however. I'd generally recommend AES. My next choices would probably be Serpent, MARS and Twofish in that order. Blowfish would come somewhere after those (though there are a couple of others that I'd probably recommend ahead of Blowfish).
Here is the script I use in a Dockerfile
based on windows/servercore
to achieve complete PowerShellGallery setup through Artifactory mirrors (require access to GitHub releases too)
ARG ONEGET_PACKAGEMANAGEMENT="https://artifactory/artifactory/github-releases/OneGet/oneget/releases/download/1.4/PackageManagement.zip"
ARG ONEGET_ZIPFILE="C:/PackageManagement.zip"
RUN $ProviderPath = 'C:/Program Files/PackageManagement/ProviderAssemblies/nuget/2.8.5.208/'; `
Invoke-WebRequest -Uri ${Env:ONEGET_PACKAGEMANAGEMENT} -OutFile ${Env:ONEGET_ZIPFILE}; `
Expand-Archive ${Env:ONEGET_ZIPFILE} -DestinationPath "C:/" -Force; `
New-Item -ItemType "directory" -Path $ProviderPath -Force; `
Move-Item -Path "C:/PackageManagement/fullclr/Microsoft.PackageManagement.NuGetProvider.dll" -Destination $ProviderPath -Force; `
Remove-Item -Recurse -Force -Path "C:/PackageManagement",${Env:ONEGET_ZIPFILE}; `
Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.208 -Force; `
Register-PSRepository -Name "artifactory-powershellgallery-remote" -SourceLocation "https://artifactory/artifactory/api/nuget/powershellgallery-remote"; `
Unregister-PSRepository -Name PSGallery;
I think you are talking about ctrl + shift + F, by default it should be on "look in: entire solution" and there you go.
the solution here worked for me : https://community.hortonworks.com/articles/4427/fix-under-replicated-blocks-in-hdfs-manually.html
su - <$hdfs_user>
bash-4.1$ hdfs fsck / | grep 'Under replicated' | awk -F':' '{print $1}' >> /tmp/under_replicated_files
-bash-4.1$ for hdfsfile in `cat /tmp/under_replicated_files`; do echo "Fixing $hdfsfile :" ; hadoop fs -setrep 3 $hdfsfile; done
Code behind solution
private void Button1_Click(object sender, RoutedEventArgs e)
{
System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
myStringBuilder.Append("Orange").AppendLine();
myStringBuilder.Append("").AppendLine();
myStringBuilder.Append("Apple").AppendLine();
myStringBuilder.Append("Banana").AppendLine();
myStringBuilder.Append("").AppendLine();
myStringBuilder.Append("Plum").AppendLine();
TextBox1.Text = myStringBuilder.ToString();
}
The best option is to use the original LESS version of bootstrap (get it from github).
Open variables.less and look for // Media queries breakpoints
Find this code and change the breakpoint value:
// Large screen / wide desktop
@screen-lg: 1200px; // change this
@screen-lg-desktop: @screen-lg;
Change it to 9999px for example, and this will prevent the breakpoint to be reached, so your site will always load the previous media query which has 940px container
If you really know what you do and you don't mind the evil ways, this is the only additional Twig extension you'll ever need:
function evilEvalPhp($eval, $args = null)
{
$result = null;
eval($eval);
return $result;
}
See for maximum numbers: http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html
TINYBLOB, TINYTEXT L + 1 bytes, where L < 2^8 (255 Bytes)
BLOB, TEXT L + 2 bytes, where L < 2^16 (64 Kilobytes)
MEDIUMBLOB, MEDIUMTEXT L + 3 bytes, where L < 2^24 (16 Megabytes)
LONGBLOB, LONGTEXT L + 4 bytes, where L < 2^32 (4 Gigabytes)
L is the number of bytes in your text field. So the maximum number of chars for text is 216-1 (using single-byte characters). Means 65 535 chars(using single-byte characters).
UTF-8/MultiByte encoding: using MultiByte encoding each character might consume more than 1 byte of space. For UTF-8 space consumption is between 1 to 4 bytes per char.
Maybe you are looking for something like this. If you want to select the complete line when it contains both "foo" and "baz" at the same time, this RegEx will comply that:
.*(foo)+.*(baz)+|.*(baz)+.*(foo)+.*
for me one case was I just missed to maven update project which caused the same issue
maven update project and try if you see any errors in POM.xml
If you need to pass the asterisk symbol, you have to wrap it with quotes.
In my case, I need to configure cors for websockets. So, I decided to put cors urls into application.yml. For prod env I'll use specific urls, but for dev it's ok to use just *.
In yml file I have:
websocket:
cors: "*"
In Config class I have:
@Value("${websocket.cors}")
private String[] cors;
The reason for this error is very simple. Your AJAX is trying to call over HTTP whereas your server is running over HTTPS, so your server is denying calling your AJAX. This can be fixed by adding the following line inside the head tag of your main HTML file:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
To elaborate on @serine's answer and illustrate working with non-trivial multi-valued condition: I had a need to show a "dim-out" overlay on an item for the boolean condition NOT a AND (b OR NOT c)
.
For background, this is a "Multiple Choice" question. If the user picks a wrong answer it becomes disabled (dimmed out and cannot be selected again). An automated agent has the ability to focus on any particular choice to give an explanation (border highlighted). When the agent focuses on an item, it should not be dimmed out even if it is disabled. All items that are not in focused are marked de-focused, and should be dimmed out.
The logic for dimming is thus:
NOT IsFocused AND (IsDefocused OR NOT Enabled)
To implement this logic, I made a generic IMultiValueConverter
named (awkwardly) to match my logic
// 'P' represents a parenthesis
// ! a && ( b || ! c )
class NOT_a_AND_P_b_OR_NOT_c_P : IMultiValueConverter
{
// redacted [...] for brevity
public object Convert(object[] values, ...)
{
bool a = System.Convert.ToBoolean(values[0]);
bool b = System.Convert.ToBoolean(values[1]);
bool c = System.Convert.ToBoolean(values[2]);
return !a && (b || !c);
}
...
}
In the XAML I use this in a MultiDataTrigger
in a <Style><Style.Triggers>
resource
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!-- when the equation is TRUE ... -->
<Condition Value="True">
<Condition.Binding>
<MultiBinding Converter="{StaticResource NOT_a_AND_P_b_OR_NOT_c_P}">
<!-- NOT IsFocus AND ( IsDefocused OR NOT Enabled ) -->
<Binding Path="IsFocus"/>
<Binding Path="IsDefocused" />
<Binding Path="Enabled" />
</MultiBinding>
</Condition.Binding>
</Condition>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<!-- ... show the 'dim-out' overlay -->
<Setter Property="Visibility" Value="Visible" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
And for completeness sake, my converter is defined in a ResourceDictionary
<ResourceDictionary xmlns:conv="clr-namespace:My.Converters" ...>
<conv:NOT_a_AND_P_b_OR_NOT_c_P x:Key="NOT_a_AND_P_b_OR_NOT_c_P" />
</ResourceDictionary>
For future Google'rs that use Laravel 5, you can now also use it with includes,
@include('views.otherView', ['variable' => 1])
If you just run jmap -histo:live or jmap -histo, it outputs the contents on the console!
(keyup.enter)="methodname()"
this should work and already mentioned in many answers, however that should be present on form tag and not on button.
If you want a query to use currently selected database. simply copy paste this query. (No modification required)
SELECT table_name ,
round(((data_length + index_length) / 1024 / 1024), 2) as SIZE_MB
FROM information_schema.TABLES
WHERE table_schema = DATABASE() ORDER BY SIZE_MB DESC;
SIMPLY, You must set initial state first
If you don't set initial state react will treat that as an uncontrolled component
Beware of circular references when DOM objects are involved:
Memory leak patterns in JavaScript
Keep in mind that memory can only be reclaimed when there are no active references to the object. This is a common pitfall with closures and event handlers, as some JS engines will not check which variables actually are referenced in inner functions and just keep all local variables of the enclosing functions.
Here's a simple example:
function init() {
var bigString = new Array(1000).join('xxx');
var foo = document.getElementById('foo');
foo.onclick = function() {
// this might create a closure over `bigString`,
// even if `bigString` isn't referenced anywhere!
};
}
A naive JS implementation can't collect bigString
as long as the event handler is around. There are several ways to solve this problem, eg setting bigString = null
at the end of init()
(delete
won't work for local variables and function arguments: delete
removes properties from objects, and the variable object is inaccessible - ES5 in strict mode will even throw a ReferenceError
if you try to delete a local variable!).
I recommend to avoid unnecessary closures as much as possible if you care for memory consumption.
Just pass the array to the Set constructor. The Set constructor accepts an iterable
parameter. The Array object implements the iterable
protocol, so its a valid parameter.
var arr = [55, 44, 65];_x000D_
var set = new Set(arr);_x000D_
console.log(set.size === arr.length);_x000D_
console.log(set.has(65));
_x000D_
You want to iterate through the list, sum all the numbers, and then divide the sum by the number of elements in the list. You can use a for loop to accomplish this.
average = 0
sum = 0
for n in numbers:
sum = sum + n
average = sum / len(numbers)
The for loop looks at each element in the list, and then adds it to the current sum. You then divide by the length of the list (or the number of elements in the list) to find the average.
I would recommend googling a python reference to find out how to use common programming concepts like loops and conditionals so that you feel comfortable when starting out. There are lots of great resources online that you could look up.
Good luck!
I had a same problem and i could fixed it! you should add C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib\x64 for 64 bit system / C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib for 32 bit system in property manager-> Linker-> General->Additional library Directories
maybe it can solve the problem of somebody in the future!
Since there were no answer on how to do this in Combine, here is the approach i used.
userInfo
and check if the current active responder is contained in it. If it's covered return keyboard frame height. If it is not covered return 0, we don't want to move the frame. For the hide notification we simply return 0.private var keyboardHeightPublisher: AnyPublisher<CGFloat, Never> {
Publishers.Merge(
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillShowNotification)
.compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect }
.map { $0.intersects(self.view.firstResponder!.frame) ? $0.height : 0 }
.map { $0 * -1 },
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillHideNotification)
.map { _ in CGFloat(0) }
).eraseToAnyPublisher()
}
In the viewDidLoad
we simply subscribe to the publisher changing the views frame accordingly.
override func viewDidLoad() {
super.viewDidLoad()
keyboardHeightPublisher.sink{ [weak self] height in
self?.view.frame.origin.y = height
}.store(in: &cancelables)
}
EDIT
Be careful! If the firstResponder
is in a subview, you have to calculate the frame corresponding to the whole screen to check if they actually intersect.
Example:
let myViewGlobalFrame = myView.convert(myView.frame, to: parentView)
Install bootstrap using npm i --save bootstrap@version
.Now,go to nodemodules folder and from bootstrap folder copy the path of 'bootstrap.min.css.js' and paste the full path(like nodemodules/bootstrap/css/bootstrap.min.css.js
) in angular.json
under script tag file and re-run the server and to check whether the installation is successful run the program in any browser you like and press F12 you'll find a part of the window gets opened,now go to elements tab open head tag and if you see bootstrap in style tag,then your installation is successful.
If your problem is like the following while using Google Chrome:
[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]
Then create a batch file by following these steps:
Open notepad in Desktop.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit
This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.
Look at the "Sprite Text" sample in the GLSurfaceView samples.
Gradle looks for gradle.properties
files in these places:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
)Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).
Reference: https://gradle.org/docs/current/userguide/build_environment.html
Jackson provides an annotation that can be used on class level (JsonIgnoreProperties).
Add the following to the top of your class (not to individual methods):
@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
...
}
Depending on the jackson version you are using you would have to use a different import in the current version it is:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
in older versions it has been:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
All these functions and random things, I think it is best to use this, and do it like this:
this.options[this.selectedIndex].text
In case you are working with environments or docker images you can really change /etc/host I recommend just changing the binding from star to 0.0.0.0.
So (basing on my case for instance) instead of:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005"
You would define it as:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0.0.0.0:5005"
You can also do this using git remote prune origin
$ git remote prune origin
Pruning origin
URL: [email protected]/yourrepo.git
* [pruned] origin/some-branchs
It prunes and deletes remote-tracking branches from a git branch -r
listing.
I found that most of the answers work but with a warning. So I have a tricky way to achieve this without any warning.
ArrayList<Question> questionList = new ArrayList<>();
...
Intent intent = new Intent(CurrentActivity.this, ToOpenActivity.class);
for (int i = 0; i < questionList.size(); i++) {
Question question = questionList.get(i);
intent.putExtra("question" + i, question);
}
startActivity(intent);
And now in Second Activity
ArrayList<Question> questionList = new ArrayList<>();
Intent intent = getIntent();
int i = 0;
while (intent.hasExtra("question" + i)){
Question model = (Question) intent.getSerializableExtra("question" + i);
questionList.add(model);
i++;
}
Note: implements Serializable in your Question class.
Allows getting any URL on your system, not just a current one.
import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))
URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
First, let's get some terminology out of the way...
upstream <= The remote git repo (likely whose master or release branch is in production)
forked-repo <= The remote [experimental git repo] (https://docs.github.com/en/github/getting-started-with-github/fork-a-repo) also known as "origin".
local repo <= The files and directories that you work with on your local workstaion, which you likely got by running a git clone my-forked-repo.git
command
local index <= Also known as your local git "stage", i.e., where you stage your files before pushing them to you remote repo.
Next, let's talk about the process of getting your changes to the upstream repo:
The process is generally to work on a feature branch and then push said branch, and open a Pull Request, either to your forked-repo's master branch or to the upstream's master branch
Create a feature branch by running git checkout -b FEATURE_BRANCH_NAME
Add/delete/modify files project files.
Add files by running git add .
Commit your files to your index by running git commit -m'My commit message'
Push your staged files by running git push origin FEATURE_BRANCH_NAME
The master and upstreambranch are entirely different commit histories message can occur when you've forked a git repository and have changed your git history.
For example, if you fork a repo and pull your forked repo to work on it locally...
If then you decide to rewrite the entire application and then decide it's a good idea to deleting all existing files, including the forked-repo's .git directory. You add new files and directories to recreate your app and also recreate your .git directory with git init
command.
Now, your application works great with your new files and you want to get it merged into the upstream repo. However, when you push your changes you get that "...entirely different commit histories..." error message.
You'll see that your original git commit will be different in your new local directory and if in your remote fork (as well as your upstream). Check this out by running this command in your current directory: git log --reverse master
. Then running the following: pushd $(mktemp -d); git clone https://github.com/my-forking-username/my-forked-repo.git; git log --reverse master; popd
You must fix your local .git repo to match your remote my-forked-repo if you want to push your commits and subsequently perform a pull request (in hopes of merging your new updates to the upstream/master branch).
git clone https://github.com/my-forking-username/my-forked-repo.git
cd my-forked-repo
git checkout -b my-new-files-branch-name
# Delete all files and directories except for the .git directory
git add .
git commit -m'Remove old files'
# Copy your new files to this my-forked-repo directory
git add .
git commit -m'Add new files'
git push origin my-new-files-branch-name
Create a PR on GitHub and request to merge your my-new-files-branch-name branch in your my-forked-repo into master.
Note: The "...entirely different commit histories..." error message can also occur in non-forked repos for the same reasons and can be fixed with the same solution above.
Ruby doesn't like that you are assigning the constant inside of a method because it risks re-assignment. Several SO answers before me give the alternative of assigning it outside of a method--but in the class, which is a better place to assign it.
You can use --dbpath flag in order to provide it with the parameters i.e, the directory address. I found it useful for Windows 10 OS.
With the default settings it is usually not required.
Yes. Fetch the repository and then cherry-pick from the remote branch.
If you want to redirect all non-www requests to your site to the www version, all you need to do is add the following code to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
I know this is a super old post, but I think what is missed is overriding __repr__
, so that __repr__ = __str__
, which is the accepted answer of this question marked duplicate.
I'm running SQL Server 2014 64 bit
on Windows 10. I tried everything, the thing that made it work was:
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 0
I don't know why the AllowInProcess turned off makes it work but that was the key in my case. Thank you for the suggestion of turning all the options off on the linkserver.
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>
Duplicate the father (or use symlink/reference).
For example, if you are using hierarchical database:
$ #each person node has two nodes representing its parents.
$ mkdir Family
$ mkdir Family/Son
$ mkdir Family/Son/Daughter
$ mkdir Family/Son/Father
$ mkdir Family/Son/Daughter/Father
$ ln -s Family/Son/Daughter/Father Family/Son/Father
$ mkdir Family/Son/Daughter/Wife
$ tree Family
Family
+-- Son
+-- Daughter
¦ +-- Father
¦ +-- Wife
+-- Father -> Family/Son/Daughter/Father
4 directories, 1 file
Here is all you need to know about relative file paths:
Starting with /
returns to the root directory and starts there
Starting with ../
moves one directory backward and starts there
Starting with ../../
moves two directories backward and starts there (and so on...)
To move forward, just start with the first sub directory and keep moving forward.
Click here for more details!
I had a problem getting this to work.
I had two dates in a db line and I need to add them to a list for yesterday, today and tomorrow.
this is my solution:
var yesterday = DateTime.Today.AddDays(-1);
var today = DateTime.Today;
var tomorrow = DateTime.Today.AddDays(1);
var vm = new Model()
{
Yesterday = _context.Table.Where(x => x.From <= yesterday && x.To >= yesterday).ToList(),
Today = _context.Table.Where(x => x.From <= today & x.To >= today).ToList(),
Tomorrow = _context.Table.Where(x => x.From <= tomorrow & x.To >= tomorrow).ToList()
};
On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with
my_func?
or
?my_func
for quick summary of both method signature and docstring.
I avoid using
my_func??
(as commented by @rohan) for docstring and use it only to check the source code
Example from this gist
func readLine(path string) {
inFile, err := os.Open(path)
if err != nil {
fmt.Println(err.Error() + `: ` + path)
return
}
defer inFile.Close()
scanner := bufio.NewScanner(inFile)
for scanner.Scan() {
fmt.Println(scanner.Text()) // the line
}
}
but this gives an error when there is a line that larger than Scanner's buffer.
When that happened, what I do is use reader := bufio.NewReader(inFile)
create and concat my own buffer either using ch, err := reader.ReadByte()
or len, err := reader.Read(myBuffer)
Another way that I use (replace os.Stdin with file like above), this one concats when lines are long (isPrefix) and ignores empty lines:
func readLines() []string {
r := bufio.NewReader(os.Stdin)
bytes := []byte{}
lines := []string{}
for {
line, isPrefix, err := r.ReadLine()
if err != nil {
break
}
bytes = append(bytes, line...)
if !isPrefix {
str := strings.TrimSpace(string(bytes))
if len(str) > 0 {
lines = append(lines, str)
bytes = []byte{}
}
}
}
if len(bytes) > 0 {
lines = append(lines, string(bytes))
}
return lines
}