_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d12901 | train | Any desktop app (including WinForms) has access to the network by default. There is no any permission system for this as for Android or iOS. But if the use has any firewall or other security software installed, he/she may be need to configure this software to allow your app to access network.
So, in your code you does not need perform any additional actions to get internet access. | unknown | |
d12902 | train | One of the best way to do this is use Dropzone js, this is a best library for uploading files using ajax and it also provides progress bar. You can use your own PHP(or any other server side language) code at server side.
I hope it will helpful.
A: img_upload.js
$(function() {
$("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
var formData = new FormData();
formData.append("hdn_pkid", $("input#hdn_pkid").val()); // if hidden variable is passed
formData.append("txt_name",$("input#txt_name").val()); // if other input types are passed like textbox, textarea, select etc...
formData.append('img_upload', $('input[type=file]')[0].files[0]); // if image or other file is passed
$.ajax({
url: "./img_upload_p.php",
type: "POST",
data: formData,
contentType: false,
processData: false,
cache: false,
})
},
});
});
img_upload_p.php
*
*Get all variables' value using POST method and store them in new variables to use and process on this page as usual.
*Get file variable like below mentioned code and then upload image using normal PHP function or your own way.
if(isset($_FILES['img_upload']))
{ $str_ = trim($_FILES['img_upload']['name']); } | unknown | |
d12903 | train | Your Linksys router at 192.168.1.1 could be blocking ActiveSync.
Also, make sure the USB connections in settings are set to ActiveSync (enable advanced network functionality), and not Mass Storage.
Here are some notes copied over from PocketPC FAQ: (re-posted here in case the website goes away)
You must follow a few preliminary steps before loading new components for Ethernet.
*
*Establish a serial cable, infrared, or USB connection to the PC with which you are going to use ActiveSync. This is required to put the PC's computer name in your Pocket PC for use with Ethernet.
*Install the Ethernet drivers from the Ethernet vendor's installation disk. This will add a Network Control Panel as well as other relevant files. This installation requires less than 250 kilobytes of free memory for storage. You may also use the built-in NE-2000 drivers if you prefer to save the storage space.
*Reset the device to load the new components.
Next, configure the Network Control Panel for Ethernet on your Pocket PC.
*
*Click Start.
*Click Settings.
*Click Network.
Figure 1: Example of the TCP/IP Properties for Socket's Low Power Ethernet CF+ Card.
*
*Enter the IP address for the Pocket PC. I suggest the TCP/IP address 192.168.1.2 with subnet mask 255.255.255.0, and the WINS server address, which is the PC's IP address (192.168.1.1 using my recommended setting).
*Leave the other fields blank.
Figure 2: Properly configured Network Control Panel settings on the Pocket PC.
Connecting
*
*Plug both the Pocket PC and the PC into the hub. (If you are using a crossover cable, you can connect the Pocket PC and PC directly without a hub.)
*Turn on the PC and the Pocket PC and plug the Ethernet PC card into your Pocket PC.
*To start an ActiveSync session, select ActiveSync on your Pocket PC (choose Start, then Programs, and then Connections). Make sure the Method is set to Network Connection and the Connect To matches the PC computer's name. Then click Connect to start ActiveSync communications.
If you enable continuous ActiveSync synchronization, your Pocket PC will stay up-to-date, downloading new e-mail, tasks, contacts, and other files and data whenever it's connected to your desktop PC.
Gotcha
After plugging your Ethernet PC card into your Pocket PC, check for a link light on the PC's Ethernet card. If it is not lit, you are having a cable or hub problem.
A: How are the network cables and devices connected? Did you use a hub or a switch (do they support MDI/X?). I ask, as normally you cannot simply connect two devices with a standard cable. Best is to use a small switch that support Auto-MDI/X and switches correctly to use normal or reversed cabling. | unknown | |
d12904 | train | Did you consider using OData? Web Api has support for OData baked in, with it you could write your queries as url's: e.g. ?$filter=Genre eq 'horror'. If, for some reason or other you, don't want your data returned as OData but would like the query syntax of OData then you could:
*
*use Linq To QueryString: this lib gives you an extension method to IQueryable that parses the query string and applies the query to any IQueryable
*transform ODataQueryOptions into a query into your database (see this MSDN article for an example that translates the query into HQL)
A: Is moving the optional parameters into the query string a viable option?
e.g. GET api/movie?genre=horror&year=2014
This would simplify your route and controller to:
config.Routes.MapHttpRoute(
name: "Movies",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
public class MovieController : ApiController
{
// GET api/<controller>?genre=<genre>&year=<year>
public IEnumerable<Movie> Get(string genre = null, int? year = null)
{
return MoviesDB.All(string genre, int year);
}
// GET api/<controller>/5?genre=<genre>&year=<year>
public Movie Get(int id, string genre = null, int? year = null)
{
return MoviesDB.ThisSpecificOne(string genre, int year, id);
}
// POST api/<controller>?genre=<genre>&year=<year>
public void Post([FromBody]Movie value, string genre = null, int? year = null)
{
}
// PUT api/<controller>/5?genre=<genre>&year=<year>
public void Put(int id, [FromBody]Movie value, string genre = null, int? year = null)
{
}
// DELETE api/<controller>/5?genre=<genre>&year=<year>
public void Delete(int id, string genre = null, int? year = null)
{
}
}
A: If you really mean the movies are stored by genre and the year, then I do believe your not so dry solution is actually correct. This does lead me to question the purpose of constructing such multi part identifier, as for instance the movie used in your example, surely the year and genre are just meta information about the movie, but not parts of the identifier. More generally speaking I'd really argue whether a composite identifier of more than two, or at least more than three parts is ever a good fit for any peace of software. A surrogate key would ease the development pain in such scenario.
Also discussing your concern about the DRY:ness of the repetition, I'd argue that as the primary key structure of an object seldom changes, it is not a really big issue. Even more so as a change in the primary key will thus always be a change breaking all backward compatibility.
As a gimmick, you could create a new class that contains the complex ID as such:
public class MovieId
{
public int Id { get; set; }
public int Yead { get; set; }
public string Genre { get; set; }
}
And then make the controller methods as such:
public Movie Get( [FromBody]MovieId id )
{
return MoviesDB.ThisSpecificOne( id );
}
This works and now the code adheres well to DRY principle. The problem is, the complex type has to be a body parameter, so the query string will not be pretty and self explanatory anymore and you'll have to be creative with the routes to distinguish the different get methods.
Moving into a business layer or a DDD layer, this kind of composite key as a value object is a very common scenario and as the query string is of no concern there, it's actually a very viable and recommended solution. | unknown | |
d12905 | train | If you want to develop your own Java applications, then yes, you need the entire JDK. However, there are several JDK alternatives available and I believe the SE JDK should be enough for you. You can find it here
A: Yes, you can, you only need JRE (runtime). Hoverwer, to develop program you do need to have JDK.
A: To run an already completed app in other machines, you just need the JRE (Java Runtime Environment) installed in those machines. You need the JDK (Java Development Kit) for development. The JDK already comes with the JRE. | unknown | |
d12906 | train | Try removing static so that
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
}
becomes
public class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
} | unknown | |
d12907 | train | We get the column names with names/colnames by looping, paste to a single string with toString, convert to a data.frame column and bind the elements (_dfr).
library(purrr)
library(dplyr)
library(stringr)
setNames(lst, str_c("df", seq_along(lst))) %>%
map_dfr(~ tibble(Var = toString(names(.x))), .id = 'Data')
-output
# A tibble: 3 × 2
Data Var
<chr> <chr>
1 df1 ID, Score, Test
2 df2 ID, Score, try
3 df3 ID, Score, weight | unknown | |
d12908 | train | You should save the relative (i.e. in percent) position of the marker on the image.
You can use getBoundingClientRect to simplify calculations:
const imgRect = myImg.current.getBoundingClientRect(); // imgRect is relative to viewport
const {clientX, clientY} = e; // clientX and clientY are relative to viewport
// since both are relative to viewport, it's useless to try to get their absolute position to the document. Simply compute their pos differences
const posXpct = (clientX - imgRect.x)*100 / imgRect.width;
const posYpct = (clientY - imgRect.y)*100 / imgRect.height;
Then you store posXpct and posYpct. And to position your marker from the previously saved values:
marker.style.position.left = posXpct+'%';
marker.style.position.top = posYpct+'%';
The additional advantage is that your marker will stay in place even if you resize physically the map (for instance on responsive devices with a width in %).
Don't forget to place the marker tip on this exact position, with something like (assuming your "tip" is at the bottom-center of the marker):
.marker {
transform: translate(-50%, -100%);
}
A: by using leaflet library you can change the address by the image | unknown | |
d12909 | train | return ~ (~0u >> 1);
~ turns on all bits in the unsigned zero. Then >> 1 shifts right, resulting in the high bit becoming zero. Then ~ inverts all bits, producing one in the high bit and zero in the rest.
Then the return converts this to int. This has implementation-defined behavior, but class assignments of this sort generally presume a behavior suitable for the exercise.
A: If you don't need a portable version, you can abuse the knowledge that integers are almost always 4 bytes.
return 0x80000000;
In fact, if you know the size of the type you're going to return, you can skip the bitwise game and cheat with the format:
*
*In 0x__, each number is 4 bits.This means 2 digits are one byte.
*You want the first bit to be 1, and all other bits to be 0.
*0x8 = 0b1000
*As such, you can represent the value as 0x80 + 2 '0's for every byte of the type past the first.
But to answer the rest of your question.
How would I go about doing this?
If you're templating, you'd (probably) use the bitwise trick the other answer suggests. Otherwise you can cheat with the above code or use a definition from limits.h (iirc).
~ (~0u >> 1);
Would be a portable solution.
Wouldn't the most negative two's comp number be dependent on how many bits the selected number is?
The most negative two's compliment is dependent upon the size of the containing variable, so I suppose you could say "selected number". In fact, the range of values depends on the size of the containing variable.
For instance, 10000 would be the most negative two's comp number of a 16 bit int?
For 16 bits, the most negative two's comp would be 0x8000, 0b1000000000000000 or -32768, depending on how you'd like it represented. | unknown | |
d12910 | train | There is a linear time algorithm for this. This algorithm is well explained by orezvani in this post on Computer Science section of stackexchange.
I translated the orezvani pseudo code in R:
max_subset<-function(S,K){
R <- S %% K
Res <- c()
for(k in 1:(ceiling(K/2)-1)){
index_k = which(R==k)
index_K_k = which(R==(K-k))
if(length(index_k) >= length(index_K_k)){
Res <- c(Res, S[index_k])
}else{
Res <- c(Res, S[index_K_k])
}
}
print(R)
Res <- c(Res, S[which(R==0)][1])
if(K %% 2 == 0){
Res <- c(Res, S[which(R==(K/2))][1])
}
return(Res)
}
I tried with different example:
*
*with S <- c(1, 7, 2, 4) and K = 3 give 1 7 4;
*with S <- c(3, 17, 12, 9, 11, 15) and K = 5 give 11 17 12 15
*with S <- c(3, 7, 2, 9, 1) and K = 3 give 7 1 3
*with S <- c(19, 10, 12, 10, 24, 25, 22) and K = 4 give 25 12 10
In order to be more understandable I tried to be as similar as possible to the pseudocode, probably my solution could be optimized using R language specific features. | unknown | |
d12911 | train | Here's a functional programming approach:
from itertools import imap, groupby
from operator import itemgetter, mul
def combine(a):
for (first, last), it in groupby(a, itemgetter(0, 2)):
yield first, reduce(mul, imap(itemgetter(1), it), 1.0), last
A: Here's a more stateful approach. (I like @Sven's better.)
def combine(a)
grouped = defaultdict(lambda: 1)
for _, value, key in a:
grouped[key] *= value
for key, value in grouped.items():
yield ('x', value, key)
This is less efficient if the data are already sorted, since it keeps more in memory than it needs to. Then again, that probably won't matter, because it's not stupidly inefficient either.
A: Given that you are ultimately going to multiply together all of the found values, instead of accumulating a list of the values and multiplying them at the end, change your defaultdict to take an initializer method that sets new keys to 1, and then multiply as you go:
data = [('x', 0.29, 'a'),
('x', 0.04, 'a'),
('x', 0.03, 'b'),
('x', 0.02, 'b'),
('x', 0.01, 'b'),
('x', 0.20, 'c'),
('x', 0.20, 'c'),
('x', 0.10, 'c'),]
from collections import defaultdict
def reduce_by_key(datalist):
proddict = defaultdict(lambda : 1)
for _,factor,key in datalist:
proddict[key] *= factor
return [('x', val, key) for key,val in sorted(proddict.items())]
print reduce_by_key(data)
Gives:
[('x', 0.011599999999999999, 'a'),
('x', 5.9999999999999993e-06, 'b'),
('x', 0.004000000000000001, 'c')] | unknown | |
d12912 | train | You can do this by setting up the idempotentKey to tell Camel how a file is considered changed. For example if the file size changes, or its timestamp changes etc.
See more details at the Camel file documentation at: https://camel.apache.org/components/latest/file-component.html
See the section Avoiding reading the same file more than once (idempotent consumer). And read about idempotent and idempotentKey.
So something alike
from("file:/somedir?noop=true&idempotentKey=${file:name}-${file:size}")
Or
from("file:/somedir?noop=true&idempotentKey=${file:name}-${file:modified}")
You can read here about the various ${file:xxx} tokens you can use: http://camel.apache.org/file-language.html
A: Setting noop to true will result in Camel setting idempotent=true as well, despite the fact that idempotent is false by default.
Simplest solution to monitor files would be:
.from("file:path?noop=true&idempotent=false&delay=60s")
This will monitor changes to all files in the given directory every one minute.
This can be found in the Camel documentation at: http://camel.apache.org/file2.html.
A: I don't think Camel supports that specific feature but with the existent options you can come up with a similar solution of monitoring a directory.
What you need to do is set a small delay value to check the directory and maintain a repository of the already read files. Depending on how you configure the repository (by size, by filename, by a mix of them...) this solution would be able to provide you information about news files and modified files. As a caveat it would be consuming the files in the directory very often.
Maybe you could use other solutions different from Camel like Apache Commons VFS2 (I wrote a explanation about how to use it for this scenario: WatchService locks some files?
A: I faced the same problem i.e. wanted to copy updated files also (along with new files). Below is my configuration,
public static void main(String[] a) throws Exception {
CamelContext cc = new DefaultCamelContext();
cc.addRoutes(createRouteBuilder());
cc.start();
Thread.sleep(10 * 60 * 1000);
cc.stop();
}
protected static RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("file://D:/Production"
+ "?idempotent=true"
+ "&idempotentKey=${file:name}-${file:size}"
+ "&include=.*.log"
+ "&noop=true"
+ "&readLock=changed")
.to("file://D:/LogRepository");
}
};
}
My testing steps:
*
*Run the program and it copies few .log files from D:/Production to D:/LogRepository and then continues to poll D:/Production directory
*I opened a already copied log say A.log from D:/Production (since noop=true nothing is moved) and edited it with some editor tool. This doubled the file size and save it.
At this point I think Camel is supposed to copy that particular file again since its size is modified and in my route definition I used "idempotent=true&idempotentKey=${file:name}-${file:size}&readLock=changed". But camel ignores the file.
When I use TRACE for logging it says "Skipping as file is already in progress...", but I did not find any lock file in D:/Production directory when I editted and saved the file.
I also checked that camel still ignores the file if I replace A.log (with same name but bigger size) in D:/Production directory from outside.
But I found, everything is working as expected if I remove noop=true option.
Am I missing something?
A: If you want monitor file changes in camel, use file-watch component.
Example -> RECURSIVE WATCH ALL EVENTS (FILE CREATION, FILE DELETION, FILE MODIFICATION):
from("file-watch://some-directory")
.log("File event: ${header.CamelFileEventType} occurred on file ${header.CamelFileName} at ${header.CamelFileLastModified}");
You can see the complete documentation here:
Camel file-watch component | unknown | |
d12913 | train | For TypeScript
intellisence / syntax highlighting / live error checking
You need the brackets-typescript plugin : https://github.com/fdecampredon/brackets-typescript
Compile to vanilla JS
You can use grunt to do that for you : https://github.com/grunt-ts/grunt-ts. It can compile your project whenever you save a file in brackets (or any other editor). The output is JavaScript
How to refer it in the html page
You point to the generated JS with a normal script tag as you do if you were just using JavaScript to begin with.
Alternatively you can use something like RequireJS http://requirejs.org/ | unknown | |
d12914 | train | I you just want the button to look like a material chip (rather than actually be a material chip), you could remove 'mat-button' from the next button and add your own class, e.g. 'next_btn':
<button class="next_btn" matStepperNext>Next</button>
You can then just style the button so it looks like a chip:
button.next_btn {
padding: 7px 12px;
border-radius: 16px;
min-height: 32px;
background-color: #e0e0e0;
color: rgba(0,0,0,.87);
box-shadow:none;
border:none;
cursor: pointer;
outline:none;
}
button.next_btn:focus
{
outline:none;
}
Example here.
A: How about inserting the button inside the chip? and managing the look... take a look here for demo
HTML:
<mat-chip-list>
<mat-chip><button mat-button matStepperPrevious>Back</button></mat-chip>
<mat-chip><button mat-button matStepperNext>Next</button></mat-chip>
</mat-chip-list>
CSS:
mat-chip{padding:0;} | unknown | |
d12915 | train | Fixed: I needed my rake task to depend on :environment so that the rails application gets initialized before the task is run.
After changing task :my_task do to
task :my_task => :environment do everything works the same in the rake task as it does in the console. | unknown | |
d12916 | train | You can clear the console window with
Console.Clear()
If you put this in between your two blocks of code you should have what you need.
You can also make a blank line by doing
Console.Writeline();
Instead of
Console.Write(new string(' ', Console.WindowWidth));
A: Did you try this...
Console.WriteLine(" Enter Your Name:");
Console.WriteLine("first name:");
string firstName = Console.ReadLine();
Console.WriteLine("last name:");
string lastName = Console.ReadLine();
Please feel free to use Console.Clear() to clear the console.
You may further print/see the values using
Consile.WriteLine("Your First Name is " + firstName + " and last name is " + lastName); | unknown | |
d12917 | train | The way I would do it is to create a frame specifically to hold just the label and the combobox. You can then easily use pack to align the label to the left and the combobox right next to it. | unknown | |
d12918 | train | The following is an attempt on joining 4 divs into a row and inserting an <hr> between the rows. Every time the expression i&&!(i%4) of loop index i is true an <hr> element is inserted before the current element.
function createUserList(usersList) {
document.getElementById("searchresult").innerHTML=usersList.map((user,i) =>`${i&&!(i%4)?"<hr>":""}
<div class="col-12 col-md-4 col-lg-3 isotope-item">
<a class="img-thumbnail-variant-3" href="single-portfolio.html">
<div class="adaptHaut">
<span class="adaptTitle">
<span class="vertBts type">${user.type}</span>
<span style="color: #92C13B;">${user.nom}</span>
</span>
<figure class="adaptImg">
<img src="images/${user.image}" alt="" width="41.8" height="31.5"/>
</figure>
</div>
<div class="caption adaptHover">
<p class="heading-5 hover-top-element adaptDescription">Compétences scientifiques,intérêt pour les technologies de laboratoire.</p>
<div class="divider"></div>
<p class="small hover-bottom-element adaptSecondDescription">Le BTS ABM est proposé à Toulouse, Montpellier et Lille.!</p>
<span class="icon arrow-right linear-icon-plus"></span>
</div>
</a>
</div>`).join("")
}
const usrs= {
"results": [{
"nom": "Analyse Biologie Médical",
"image": "MBS-phot-2.jpg",
"type": "BTS"
},
{
"nom": "Diététique",
"image": "diet.webp",
"type": "BTS"
},
{
"nom": "Nutrition Santé",
"image": "m2ns.jpg",
"type": "BTS"
},
{
"nom": "Nutrition Santé",
"image": "dieteticien.jpg",
"type": "BACHELOR"
},
{
"nom": "Analyse Biologie Médical",
"image": "MBS-phot-2.jpg",
"type": "BTS"
},
{
"nom": "Diététique",
"image": "diet.webp",
"type": "BTS"
},
{
"nom": "Nutrition Santé",
"image": "m2ns.jpg",
"type": "BTS"
},
{
"nom": "Nutrition Santé",
"image": "dieteticien.jpg",
"type": "BACHELOR"
}
]
}
createUserList(usrs.results)
.isotope-item {display:inline-block}
<h2>Results</h2>
<div id="searchresult"></div>
A: Instead of creating a new element on each iteration use map to create a template string for each object, and then join that array of strings (map returns a new array) into one HTML string. Then assign that HTML to a containing element.
(Sidenote: if your data is tabular you should probably use a table.)
Here's a pared back example to show you how map/join work together.
const arr = [
{ name: 'Rita', nom: 18, img: 'img1' },
{ name: 'Sue', nom: 19, img: 'img2' },
{ name: 'Bob', nom: 40, img: 'img3' }
];
// Accepts the array of objects
function createHTML(arr) {
// `map` returns a new array of HTML strings which
// is `joined` up before that final string is returned
// from the function
return arr.map(obj => {
const { name, nom, img } = obj;
return `<div>${name} - ${nom} - ${img}</div>`;
}).join('');
}
// Get the container and assign the result of calling the
// function with the array of objects
const container = document.querySelector('.container');
container.innerHTML = createHTML(arr);
<div class="container"></div>
Additional documentation
*
*Destructuring assignment | unknown | |
d12919 | train | I don't know exactly what your search strategy is here, but if you want to see all records going back 7 days to the past, you may use:
SELECT status, dateTime
FROM database
WHERE dateTime >= date('now', '-7 day'); | unknown | |
d12920 | train | Is there a reason you are using ScenePhase
You can just add this code at file scope
extension UINavigationController {
override open func viewDidLoad() {
super.viewDidLoad()
let standard = UINavigationBarAppearance()
standard.backgroundColor = .blue
let compact = UINavigationBarAppearance()
compact.backgroundColor = .green
let scrollEdge = UINavigationBarAppearance()
scrollEdge.backgroundColor = .red
navigationBar.standardAppearance = standard
navigationBar.compactAppearance = compact
navigationBar.scrollEdgeAppearance = scrollEdge
}
} | unknown | |
d12921 | train | using namespace std; combined with too much header inclusions is likely the culprit here - there's a reason why it has been repeated over and over again here on SO not to use it. By doing that, the compiler sees bind and thinks you mean std::bind from <functional>, not ::bind for sockets. So either do the right thing and review if you really need to include all those headers and get rid of that using declaration, or use ::bind (edit: or both - it's not bad to use :: to indicate you want to use some standard API function from the global namespace) | unknown | |
d12922 | train | To answer my own questions:
Going back to at least version 8 the default seed was 123456789 but as Nick Cox points out in comments above this doesn't mean all versions of Stata would produce the same sequence of random numbers based on that seed because the random number generator has changed over time.
The default sortseed seems to be 1001:
. query sortseed
. di r(sortseed)
1001 | unknown | |
d12923 | train | No reason you cant install phpmyadmin on your new EC2 server. Just remember to open up the necessary ports through amazons security group, and if you dont want the whole world to be able to access it, you can restrict the ports to only IP addresses you use.
AWS SECURITY GROUPS | unknown | |
d12924 | train | Ok I got it figured out. I had to move $(':checkbox').change(evaluateCheckbox); from the document.ready to the function that gets ran after the script returns from the .cs file.
$(document).ready(function(){
//buildCheckboxes();
google.script.run.withSuccessHandler(buildCheckboxes).withFailureHandler(fail).getNumber();
});
function buildCheckboxes(num){
if (!num){ var num=3;}
$("#checkboxes").empty();
for (var i=0;i<3;i++){
$("#checkboxes").append('<input type="checkbox" name="cb_'+i+'" value="v2" >Checkbox '+i+'<br><input type="button" id="cb_'+i+'" value="Button"><br>');
$(":button").hide();
}
$(':checkbox').change(evaluateCheckbox); //Move this here to make it work.
}
function evaluateCheckbox(){
if (this.checked) {
$("#"+this.name).show();
} else {
$("#"+this.name).hide();
}
} | unknown | |
d12925 | train | Give this a try. Add it under 'text:' like:
text: 'Total memebers of the club',
textStyle: {
color: '#ed2d2e'
} | unknown | |
d12926 | train | To match everything before :, use ^[^:]+ regex.
See demo (it will work with Java, too, with find()).
The matches() in Java just must match the whole string, that is why regexplanet.com says there is no match (but find() shows success).
If you want to use matches(), you need to extend the regex to the string end, and only grab the first capturing group: ([^:]+):.*.
Here is a link to a sample program showing how to capture multiple matches.
String str = "%ROUTING-FIB-3-ASSERT more words here\n%HA-REDCON-4-FAILOVER_REQUEST[0x767443be74] Record Reboot History, reboot cause = 0x4000004, descr = Cause: Initiating switch-over.";
String rx = "(?i)(%[a-z_-]+-[0-6]-[a-z_-]+)";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println(m.group(0));
} | unknown | |
d12927 | train | Check to make sure that folder location exists on the computer.
SAS will not create the folder for you if it doesn't already exist. | unknown | |
d12928 | train | As the adsbackup.exe tool basically just runs the sp_BackupDatabase / sp_BackupFreeTables stored procedures, you can easily replace it with the newer asqlcmd.exe tool:
https://devzone.advantagedatabase.com/dz/webhelp/Advantage12/index.html?master_sql_command_line_switches.htm
Maybe you have more luck with the command line switches there.
On the other hand you say that you don't have an adssys password. First of all this is a big security risk!
I don't know if it is possible, but maybe you can add a second user for backup purposes that has a password. That way you could circumvent the password problem with adsbackup.exe.
Another approach would be to write your own tool in any language supported by ADS. If you have a talented programmer at hand that shouldn't be a big deal.
Finally I have another idea: Have you tried quoting your empty password with single or double quotes? Maybe the adsbackup.exe tool does quote processing and / or trimming on the password switch. You could also try passing a quoted string that contains of one or more white space characters. | unknown | |
d12929 | train | It's not quite clear how you are passing this value to the controller action. You have only shown some @Html.DisplayFor(m=>m.CarState) but obviously this only displays a label in the view. It doesn't send anything back to the server. If you want to send some value back you will have to use an input field inside the form.
For example:
@Html.EditorFor(m => m.CarState)
or use a HiddenFor field if you don't want the user to edit it.
In any case you need to send that value to the server if you expect the model binder to be able to retrieve it. The model binder is not a magician. He cannot invent values. He binds values to your model from the Request. | unknown | |
d12930 | train | The problem is likely to be the ZeroBytePadding. The one of Bouncy always adds/removes at least one byte with value zero (a la PKCS5Padding, 1 to 16 bytes of padding) but the one of PHP only pads until the first block boundary is encountered (0 to 15 bytes of padding). I've discussed this with David of the legion of Bouncy Castle, but the PHP zero byte padding is an extremely ill fit for the way Bouncy does padding, so currently you'll have to do this yourself, and use the cipher without padding.
Of course, as a real solution, rewrite the PHP part to use AES (MCRYPT_RIJNDAEL_128), CBC mode encryption, HMAC authentication, a real Password Based Key Derivation Function (PBKDF, e.g. PBKDF2 or bcrypt) and PKCS#7 compatible padding instead of this insecure, incompatible code. Alternatively, go for OpenSSL compatibility or a known secure container format. | unknown | |
d12931 | train | The API/server is not 'returning' expired; it is using a certificate/chain which your nodejs client is rejecting, because the cert is from LetsEncrypt which by default still uses a 'compatibility' root (DSTX3) that expired last Sept, but which most clients (including the sslchecker you used) can replace with the newer and still-valid ISRG root.
nodejs uses OpenSSL with by default its own hardcoded list of CA certs, which in nodejs 6 did not include the ISRG root; further, depending on your system and build, it may be using an older version of OpenSSL which doesn't do the replacement-with-new-root correctly. To solve this problem you must have recentish (>=1.1.0) OpenSSL and add the ISRG root; you can do the latter in code by setting the ca option, or with environment variable NODE_EXTRA_CA_CERTS.
See Axios fails with 'certificate has expired' when certificate has not expired
LetsEncrypt root certificate expiry breaks Azure Function Node application
Giving Axios LetsEncrypt's New Root Certificate On Old Version Of Node | unknown | |
d12932 | train | Just set runat="server" to the div
<div id="testDiv" runat="server"></div>
and add the control like this
testDiv.Controls.Add(dtStatuses); | unknown | |
d12933 | train | Using a grid for these problems is the right choice! What you are trying to achieve is a bit more complex than the use case of flexbox.
By using grid-template-columns instead of grid-template-areas, and the :first-child selector, it it possible to achieve what you describe.
Given this example HTML:
<div>
<article>Item 1</article>
<article>Item 2</article>
<article>Item 3</article>
<article>Item 4</article>
</div>
You can use this CSS:
div {
display: grid;
grid-template-columns: 1fr 1fr;
}
article {
grid-column: 2;
}
article:first-child {
grid-column: 1;
}
Have a look at this fiddle to see an example.
https://jsfiddle.net/h9k5x7uf/
If you want to make this more dynamic or server rendered, replace :first-child with some helper classes instead.
.pull-left { grid-column: 1; }
.pull-right { grid-column: 2; } | unknown | |
d12934 | train | You want links on Nav Bar to show when the site is viewed via PC or Laptop screen. And you want the links to collapse in button when site is viewed via mobile.
When viewed on PC Screen:
I did it with Bootstrap, you can also use jQuery for simplicity.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="container-fluid">
<div class="row">
<nav class="navbar navbar-expand-md navbar-light">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarToggler1" aria-controls="navbarToggler1" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggler1">
<div id="right-menu" class="col-md-3">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#features">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Blog</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#footer">Contact</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
</div>
</div>
Using simple jQuery
#show{
display:none;
}
#content{
display:none;
}
@media only screen and (max-width: 600px)
{
div{
display:none;
}
#show{
display:inline;
}
}
<button id="show">Show</button>
<div id="content">
<ul>
<li>
pricing
</li>
<li>
features
</li>
</ul>
</div>
<div>
<ul>
<li>
pricing
</li>
<li>
features
</li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$("#show").click(function()
{
$("#content").toggle();
});
</script>
Live Result with Code | unknown | |
d12935 | train | Do this:
TypedArray ta = getResources().obtainTypedArray(R.array.array_category_icons);
Drawable[] icons = new Drawable[ta.length()];
for (int i = 0; i < ta.length(); i++) {
int id = ta.getResourceId(i, 0);
if (id != 0) {
icons[i] = ContextCompat.getDrawable(this, id);
}
}
ta.recycle(); | unknown | |
d12936 | train | You can do it using the C function strtok to tokenize the buffer
void setup() {
Serial.begin(115200);
char buffer[20] = "+CBC: 1,66,3.900V";
const char* delims = " ,V";
char* tok = strtok(buffer, delims); // +CVB:
tok = strtok(NULL, delims);
int first = atoi(tok);
tok = strtok(NULL, delims);
int second = atoi(tok);
tok = strtok(NULL, delims);
float voltage = atof(tok);
Serial.println(first);
Serial.println(second);
Serial.println(voltage);
}
void loop() {
}
A: This fixed it:
float getVoltage() {
if (atCmd("AT+CBC\r") == 1) {
char *p = strchr(buffer, 'V');
if (p) {
p -= 5; // get voltage
double vo = atof(p) ;
//printf("%1.3f\n", vo);
return vo;
}
}
return 0;
} | unknown | |
d12937 | train | You can toggle classes using the Alpine.js x-bind:class object syntax, eg. :class="{ 'active classes': openTab === 1 }" for your first tab, see the following snippet. You could also bind :disabled="openTab !== 1" to disable the button (for the first button).
<div aria-label="Lista" data-balloon-pos="up" id="show-tip">
<button :class="{ 'active classes': openTab === 1 }" class="p-1 mr-1 text-gray-500 rounded-lg outline-none active:text-gray-200 hover:text-gray-200 focus:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 1" autofocus>
<svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M9 2a1 1 0 000 2h2a1 1 0 100-2H9z"></path><path fill-rule="evenodd" d="M4 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v11a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm3 4a1 1 0 000 2h.01a1 1 0 100-2H7zm3 0a1 1 0 000 2h3a1 1 0 100-2h-3zm-3 4a1 1 0 100 2h.01a1 1 0 100-2H7zm3 0a1 1 0 100 2h3a1 1 0 100-2h-3z" clip-rule="evenodd"></path></svg>
</button>
</div>
<div aria-label="Alocação de Ativos" data-balloon-pos="up" id="show-tip">
<button :class="{ 'active classes': openTab === 2 }" class="p-1 mr-1 text-gray-500 rounded-lg outline-none hover:text-gray-200 focus:text-gray-200 active:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 2">
<svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M2 10a8 8 0 018-8v8h8a8 8 0 11-16 0z"></path><path d="M12 2.252A8.014 8.014 0 0117.748 8H12V2.252z"></path></svg>
</button>
</div> | unknown | |
d12938 | train | You mean like this?
Function MyProp(ByVal r as Range) as String
MyProp = r.Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)
End Function
...
Cells(i,j).Formula = "="& MyProp( Cells(i,j) )
This of course makes a cell reference itself, which is generally a bad idea and may lead to circular references. Best if you describe more on what you are trying to do in order to get better answers.
A: As mentioned in the comments this cannot be done in the way you describe. There are two alternatives:
*
*Write a Private Function that you call with your input and expected output (more complicated)
*Write a loop with the code only appearing once. (less code)
To write a loop for all cells from A1 to Last used row, last used column:
Dim LastRow As Long, LastCol As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
For i = 1 To LastRow
For j = 1 to LastCol
`Do your stuff here
Next j
Next i
Edit:
I'm going to assume you need to invest in the Range.Offset() method found here because right now, you are setting the cell's formula as equal to itself... | unknown | |
d12939 | train | Most likely one is the "real" (or "global") ID, the other one is an "App Scoped ID". See the changelog for more information: https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api
You don´t get the global IDs anymore (except for browsing through a Facebook Page), and there is no way to match global IDs with App Scoped ones. | unknown | |
d12940 | train | You need to create a shared onchange function, then apply that to each element:
// Iterate over each element with the fileUpload class and assign the handler
[].forEach.call(document.getElementsByClassName('fileUpload'), function(element) {
element.onchange = onFileChanged;
});
// Shared handler for the event
function onFileChanged() {
alert("changed");
var field = this; // 'this' is the current file element
var file = field.files[0];
var filename = this.value;
alert(filename);
var a = filename.split(".");
alert(a);
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
var suffix = a.pop().toLowerCase();
//if( suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'pdf' && suffix != 'doc'){
if (!(suffix in {jpg:'', jpeg:'', png:'', pdf:'', doc:''})){
field.value = "";
alert('Please select an correct file.');
}
};
<input type="file" name="image" id="fileUpload">
<input type="file" name="image" class="fileUpload">
<input type="file" name="image" class="fileUpload">
A: This
getElementsByClassName('fileUpload')
returns an Array of items and not a single one. Just make a loop through instead:
var array = getElementsByClassName('fileUpload');
for (var i=0;i<array.length;i++) {
array[i].onchange = ...
}
A: <!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
<script>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
</script>
<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>
</body>
</html>
Here, good luck, useful me, thanks you. | unknown | |
d12941 | train | Thank you for helping. I solved my problem with the componentDidUpdate() method. As describe in the documentation https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/postrender_with_componentdidupdate.html
For now my final solution:
componentDidUpdate() {
const imageName: string = this.props.imageName;
const dataProvider = new DataProvider(DataProvider.DBNAME);
dataProvider.loadImage('somedoc', imageName)
.then((response: any) => {
let {imageDataUrl}: any = this.state;
if (imageDataUrl !== response) {
imageDataUrl = response;
this.setState({imageDataUrl});
}
})
.catch((error: any) => console.log(error));
}
A: Since your loadData function is asynchronous, data.image will be an empty string when the Child component is mounted.
You could e.g. wait with the rendering of the Child component until the request has finished.
Example
class Parent extends Component<Props> {
constructor(props: Props) {
super(props);
this.state = {
data: {
image: null
}
};
}
public componentDidMount() {
const dataProvider = new DataProvider(DataProvider.DBNAME);
dataProvider
.loadData("somedoc")
.then((data: object) => this.setState({ data }));
}
public render() {
const { data }: any = this.stat;
if (data.image === null) {
return null;
}
return <Child image={data.image} />;
}
} | unknown | |
d12942 | train | You can list the dates you want and aggregate:
select m.eom, sum(s.sales)
from (select '2020-01-31' as eom union all
select '2020-02-29' union all
. . .
) m left join
sales s
on s.date < m.eom
group by m.eom;
Note that you can also generate the dates using a recursive CTE or calendar table.
For this particular query, you could also use a cumulative sum:
select last_day(date) as eom, sum(sales),
sum(sum(sales)) over (order by last_day(date))
from sales
group by eom;
That works for your particular example, but might not work for other logic. | unknown | |
d12943 | train | In .net 4.0. ValidationSummary returns MvcHtmlString not string as with 3.5.
A: Html.ValidationSummary() returns MvcHtmlString, not a normal string. So, try this:
<% if (MvcHtmlString.IsNullOrEmpty(Html.ValidationSummary())) { %>
A: Thanks folks. This topic helped me when I encountered the same error:
"Message":"The best overloaded method match for 'string.IsNullOrEmpty(string)' has some invalid arguments","Data":null,"InnerException":null,"HelpURL":null
It happened to me that I passed a dynamic object into string.IsNullOrEmpty(), where the parameter was type of JValue rather than string at runtime. So I have to firstly explicitly convert the parameter to string:
var isValid = !string.IsNullOrEmpty(obj.Value);
It is a similar case with MvcHtmlString.
A: In the new MVC, the Html.ValidationSummary() returns a MvcHtmlString, not a normal string. You could use ValidationSummary().ToString() or ToHtmlString() to make it a string. | unknown | |
d12944 | train | The radius of an arc is measured from its center. You're using almost the entire view's width/height, so that the arc will be drawn outside of the visible area. Use a smaller radius and you'll see your arc.
Btw, if all you want is to draw a circle (an arc with an angle of 2π is the same), CGContextAddEllipseInRect is easier to use.
A: you are drawing the circle just outside the view. CGContextAddArctakes radius as parameter. In your case, you are giving the method diameter.
Quick fix:
radius/=2;
A: Your example is working. It's actually drawing, but you can't see the circle, as the radius variable probably get's a big value that make the circle to be drawn outside the bounds of the view.
Just replace manually radius value with a value, say 20, and you'll see that's working fine.
Regards | unknown | |
d12945 | train | Is your client perhaps running Windows?
The "case insensitive" setting in Samba is only useful if the client supports case insensitive filename lookups. Windows does not, and it will have trouble if you have two files with the same name but a different case.
Clients that do support case insensitivity include the SMB support in the Linux kernel and Samba's own "smbclient". | unknown | |
d12946 | train | You do not need to set any height or width to images in Bootstrap carousel if you are using them as img source. You need to add height only if you are using them as a background image. For this, you need to add height to .item class and set the background properties for the same. | unknown | |
d12947 | train | Use filter like this
https://api.insight.ly/v2.1/contacts?$filter=LAST_NAME%20eq%20'Jones' | unknown | |
d12948 | train | You'll want to use the Window.Activated event to detect when your application's window is brought into focus:
From the documentation:
A window is activated (becomes the foreground window) when:
*
*The window is first opened.
*A user switches to a window by selecting it with the mouse, pressing ALT+TAB, or from Task Manager.
*A user clicks the window's taskbar button.
Or you could use the Application.Activated event.
Clicking on a control of an already active window can also cause the Window.Activated event to fire, so if the issue is that it's firing too often, you'll probably want to watch for when the application toggles between being active and deactive.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Application.Current.Activated += CurrentOnActivated;
Application.Current.Deactivated += CurrentOnDeactivated;
}
private bool isDeactivated = true;
private void CurrentOnDeactivated(object sender, EventArgs eventArgs)
{
isDeactivated = true;
//handle case where another app gets focus
}
private void CurrentOnActivated(object sender, EventArgs eventArgs)
{
if (isDeactivated)
{
//Ok, this app was in the background but now is in the foreground,
isDeactivated = false;
//TODO: bring windows to forefont
MessageBox.Show("activated");
}
}
}
A: I think what you are experiencing is the window Owner not being set on your child window.
Please refer to Window.Owner Property
When a child window is opened by a parent window by calling
ShowDialog, an implicit relationship is established between both
parent and child window. This relationship enforces certain behaviors,
including with respect to minimizing, maximizing, and restoring.
-
When a child window is created by a parent window by calling Show,
however, the child window does not have a relationship with the parent
window. This means that:
*
*The child window does not have a reference to the parent window.
*The behavior of the child window is not dependent on the behavior of the parent window; either window can cover the other, or be
minimized, maximized, and restored independently of the other.
You can easily fix this by setting the Owner property in the child window when before calling Show() or ShowDialog()
Window ownedWindow = new Window();
ownedWindow.Owner = this; // this being the main or parent window
ownedWindow.Show();
Note : if conforming to an MVVM pattern, this can become a little
more cumbersome, however there is plenty of resources on how to link owner and parent windows. | unknown | |
d12949 | train | It depends on the platform. To do it at runtime, on Linux, you use dlopen, on windows, you use LoadLibrary.
To do it at compile time, on windows you export the function name using dllexport and dllimport. On linux, gcc exports all public symbols so you can just link to it normally and call the function. In both cases, typically this requires you to have the name of the symbol in a header file that you then #include, then you link to the library using the facilities of your compiler.
A: There are two ways of loading shared objects in C++
For either of these methods you would always need the header file for the object you want to use. The header will contain the definitions of the classes or objects you want to use in your code.
Statically:
#include "blah.h"
int main()
{
ClassFromBlah a;
a.DoSomething();
}
gcc yourfile.cpp -lblah
Dynamically (In Linux):
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen ("libm.so", RTLD_LAZY);
if (!handle) {
fprintf (stderr, "%s\n", dlerror());
exit(1);
}
dlerror(); /* Clear any existing error */
cosine = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "%s\n", error);
exit(1);
}
printf ("%f\n", (*cosine)(2.0));
dlclose(handle);
return 0;
}
*Stolen from dlopen Linux man page
The process under windows or any other platform is the same, just replace dlopen with the platforms version of dynamic symbol searching.
For the dynamic method to work, all symbols you want to import/export must have extern'd C linkage.
There are some words Here about when to use static and when to use dynamic linking.
A: You need to #include any headers associated with the shared library to get the declrarations of things like ClassFromBlah. You then need to link against the the .so - exactly how you do this depends on your compiler and general instalation, but for g++ something like:
g++ myfile.cpp -lblah
will probably work.
A: It is -l that link the archive file like libblah.a or if you add -PIC to gcc you will get a 'shared Object' file libblah.so (it is the linker that builds it).
I had a SUN once and have build this types of files.
The files can have a revision number that must be exact or higher (The code can have changed due to a bug). but the call with parameters must be the same like the output. | unknown | |
d12950 | train | Finally, I found the python process has a lot of threads, then I get a clue about the motor 'ThreadPoolExecutor'.
code in motor 2.1:
if 'MOTOR_MAX_WORKERS' in os.environ:
max_workers = int(os.environ['MOTOR_MAX_WORKERS'])
else:
max_workers = tornado.process.cpu_count() * 5
_EXECUTOR = ThreadPoolExecutor(max_workers=max_workers)
I set MOTOR_MAX_WORKERS=1 and the mem_usage keeps in low level.
I deploy my project in docker.But, the cpu of the container is not exclusive.I guess this is the reason of 'max_workers' is irrational.
My fault... | unknown | |
d12951 | train | If you're using the DataImportHandler, you can have an <entity> for the question and then specify a sub-entities for the answers. For example:
<document name="questions">
<entity name="question" query="select id, question from questions">
<field column="id" name="id" />
<field column="question" name="question" />
<entity name="answer"
query="select question_id, answer from answers"
cacheKey="question_id"
cacheLookup="question.id"
processor="CachedSqlEntityProcessor">
<field name="answer" column="answer" />
</entity>
</entity>
</document>
Note that this example uses CachedSqlEntityProcessor to avoid hitting the database unnecessarily. | unknown | |
d12952 | train | Fixed by uninstalling and reinstalling TS using
npm uninstall typescript --save
npm install typescript --save-dev
A: If you are using Visual Studio, and combine front-end with backend in one solution, you should check if the version of package Microsoft.TypeScript.MSBuild is up to date.
A: I have fixed the error by doing the following in my project with storybook
npm i [email protected]
npm i @types/[email protected] | unknown | |
d12953 | train | Reading the docs can often provide answers to such questions. For example, the documentation for curve_fit() at https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html says:
Returns: popt : array
Optimal values for the parameters so that the sum of the squared residuals of f(xdata, *popt) - ydata is minimized
pcov : 2d array
The estimated covariance of popt. The diagonals provide the variance of the parameter estimate. To compute one standard deviation errors on the parameters use perr = np.sqrt(np.diag(pcov)).
How the sigma parameter affects the estimated covariance depends on absolute_sigma argument, as described above.
which is to say: use p_sigma = np.sqrt(np.diag(pcov))
Allow me to suggest that for curve-fitting to Gaussian and Lorentzian models, you might find lmfit (https://lmfit.github.io/lmfit-py/) helpful. It provides built-in version for these and other Models. Among other features, it can print a nicely formatted report for such a fit that includes uncertainties.
For an example, see https://lmfit.github.io/lmfit-py/builtin_models.html#example-1-fit-peaked-data-to-gaussian-lorentzian-and-voigt-profiles | unknown | |
d12954 | train | I don't know why but the problem was with the mysql.sock file. So, you can remove it or move it somewhere else and try executing the command again. At least in my case, the problem is solved and mongosqld is running! Maybe it helps someone in the future and maybe someone let us know what's the exact reason!
A: Thanks Aboozar.
Mongosqld will - by default - attempt to bind to unix domain sockets on OSes where that exists. The error you saw above is an indication that some other process was already bound to mysql.sock - this could have been another instance of mongosqld or a mysqld server.
To reliably avoid situations like this in the future, you can start mongosqld with the additional flag --noUnixSocket. | unknown | |
d12955 | train | your issue can be found with
{filterArray.length > 0 ? (
<ProductGrid products={filterArray} />
) : (
<ProductGrid products={products} />
)}
when the app render's the content after clicking the size filter, your filterArray is empty and therefore returns the products array which contains all your data | unknown | |
d12956 | train | public class RegexExample {
/**
* @param args
*/
public static void main(String[] args) {
String href= "<a href=\"w3schools.com\">Visit W3Schools.com!</a>";
String regexOr = "(?<=[>])(\\\\?.)*?(?=[<])";
Pattern pattern = Pattern.compile(regexOr);
Matcher matcher = pattern.matcher(href);
if (matcher.find()) {
String enrichedValue = matcher.group();
System.out.print(enrichedValue);
}
}
}
This will print:
Visit W3Schools.com!
Keep in mind \ becomes \\ in java, it needs to be escaped
Full example:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
private static final Pattern ptninhref;
static{
ptninhref = Pattern.compile("(?<=[>])(\\\\?.)*?(?=[<])");
}
/**
* @param args
*/
public static void main(String[] args) {
String href= "<a href=\"paypal.com/signin/\">https://www.paypa1.com/signin/</a>";
List<String> results = captureValuesinhref(href);
for(String result:results){
System.out.print(result);
}
}
public static List<String> captureValuesinhref(String largeText){
Matcher mtchinhref = ptninhref.matcher(largeText);
List<String> inHREF = new ArrayList<String>();
while(mtchinhref.find()){
inHREF.add(mtchinhref.group());
}
return inHREF;
}
}
prints:
https://www.paypa1.com/signin/ | unknown | |
d12957 | train | This appears to be an issue on Apple's servers that started a few days ago. See this forum thread:
https://forums.developer.apple.com/thread/80546
Apple's server team is said to be addressing it now. Here's a quote from an Apple staff member on that thread:
"I've forwarded all of these bug reports to the Apps Ops Engineering QA team for thei review. For everyone else, by all means submit bug reports, but at this point, I'm not going verify that the bug reports are passed on to Apps Ops Engineering QA. The server team's attention is now on this issue." | unknown | |
d12958 | train | I think, that rstrip() method should help you:
palabras = [elem.findAll("td")[1].get_text().rstrip() for elem in wiki_filas[1:]]
frecuencia = [elem.findAll("td")[2].get_text().rstrip() for elem in wiki_filas[1:]]
You can also use lstrip for left side and strip() method for both sides of string.
edit: this removes all whitespaces.
A: \n is a newline.
You can remove it either with .replace("\n", ""):
palabras = [elem.findAll("td")[1].get_text().replace("\n", "") for elem in wiki_filas[1:]]
frecuencia = [elem.findAll("td")[2].get_text().replace("\n", "") for elem in wiki_filas[1:]]
Alternatively, .strip() removes any surrounding whitespace. | unknown | |
d12959 | train | Take a look to the Clean-up process settings: http://blogs.lessthandot.com/index.php/ITProfessionals/ITProcesses/don-t-forget-to-clean
Wayback Machine Archive Link
By default TeamCity kepts everything forever, you must configure clean-up rules for each project. | unknown | |
d12960 | train | No, that's not possible. Could you please provide more description about how the worker role "stop saving new data to table"? Did it encountered failures? If so, what's the detailed error message? Or did it make no progress while writing table entities? | unknown | |
d12961 | train | Your indentation problem you can easily solve by multiplying the $level by the number of pixels for a simple indent (3px in your case).
For the bold problem you need a different approach as in your current code, you don't know if the item has any children. The solution to that would be to first get the children in a variable, then add the bold style if any exist, echo the item and only then process the children.
Personally I would first get all data from the database in one pass, then build the hierarchical structure and then use a different function to generate the html. See for example this question for more details.
Edit: Based on your updated question; you can easily optimize it and get rid of the query in the while loop (I'd still go for the option in the previous paragraph by the way...):
*
*Don't echo anything, just return a string from your function
*Get rid of the query in the while function
*Swap the echo and the function call lines
The result in your function would be something like:
....
$html = '';
while (...)
{
$children_html = generateOptions($data[0], $level+1, $padding, $db);
$optstyle = empty($children_html) ? 'std' : 'bold';
$html .= generateOption($optstyle.'option', $data, $padding);
$html .= $children_html;
}
return $html;
and just do a echo generateOptions(...) where you called the function before.
A: It looks like you might need to be adding more &nbps;'s to your padding where you're just assigning it to one space.
else {$optstyle='std'; $padding=' ';}
to
else {$optstyle='std'; $padding .=' ';}
A: You are trying to map a flat data structure (list) into a tree visually.
Before you can do this in a simple manner, you need to gather the date that is influencing the display to the list.
E.g. you could add a level per entry (1, 2 or 3), which looks like that being your recursive structure already!
Then you pass the modified list to the display routine, that only needs to decide based on the level how to display the entry, for each level:
*
*font-weight: bold;
*padding-left: 3px; font-weight: bold;
*padding-left: 6px;
The easiest thing to achieve that is to assing a class attribute to the elements parent HTML tag like level-1, level-2 etc..
You already have a $level variable, but I see an error, you increment it all the time, but you only need to pass the value:
generateOptions($data[0], $level+1, $padding, $db);
It might be that this already solves your issue. | unknown | |
d12962 | train | This is the important message in the logs:
2016-10-31T14:27:43.507545+00:00 app[worker.1]: sh: 0: Can't open target/bin/worker
Does your maven build generate this target/bin/worker script?
I would not expect the CLI deploy to work because it does not include the target dir by default. But you can include it with the --include option. | unknown | |
d12963 | train | is embedding the username and password in the code safe
Of course not. Storing credentials without decent protection is never safe. Every user having access to the code or the executable can extract the credentials.
If I were you, I would store those credentials in an encrypted file on the machine it runs in a place where only the service user can access it. Encrypt the file with a device-specific key, so even if other users can obtain the file, it is useless to them since they can't decrypt it.
A: It's not safe in that anyone with access to that code or the application can get the password to the account with ease.
It's about risk vs reward. If a malicious player has access to the code or server then surely you have bigger issues to worry about than someone being able to access a mail account that can easily be recovered or shut down.
Is it worth going through extra trouble to prevent this outcome? It's up to you.
Arguably the configuration details should at least be in App.config so that they can be easily changed if a password expires, otherwise you'd have to recompile and redeploy the entire solution.
Ideally you should look into the various means available to you to perform encryption of your configuration file if you want to be as safe as possible. A simple search for c# encrypt configuration has enough material to get you started. | unknown | |
d12964 | train | Try using JavaScript to change the classes then you only need one class to determine which one is clicked.
Here is an example:
JS:
$("UL.features LI A").click(function(){
$("UL.features LI A").removeClass('clicked');
$(this).addClass('clicked');
});
CSS:
A.clicked {
color:#71a1ff !important;
}
Here it is in jsfiddle:
http://jsfiddle.net/57PBm/
EDIT: This solution uses JQuery which will I would definitely suggest using if you are not already
A: Rewrite JS code to:
function swapIphoneImage( elThis, tmpIPhoneImage ) {
var el = document.getElementByClassName('clicked-class');
var iphoneImage = document.getElementById('iphoneImage');
iphoneImage.src = tmpIPhoneImage;
el.className = '';
elThis.className = 'clicked-class';
}
and each button to:
<li><a id="my-link" href="javascript:swapIphoneImage(this, 'wscalendarws.png');" title="">HaPPPs Calendar</a></li>
You don't need to set up 5 CSS classes for the same thing.
A: You are changing every element to a clicked class. Just pass in a number to the function that identifies which button to color blue, then color that one blue and all the others green via JS. | unknown | |
d12965 | train | your task is quite easy with dplyr, but there is a variety of approaches.
library(dplyr)
df %>% group_by(Item) %>% filter(ID == min(ID, na.rm = TRUE))
Source: local data frame [3 x 3]
Groups: Item [3]
Item Cost ID
<fctr> <dbl> <dbl>
1 A 4 1
2 B 39 10
3 C 290 15
Data used:
structure(list(Item = structure(c(1L, 1L, 2L, 2L, 2L, 3L, 3L), .Label = c("A",
"B", "C"), class = "factor"), Cost = c(4, NA, 39, NA, NA, 290,
NA), ID = c(1, 3, 10, 18, 21, 15, NA)), .Names = c("Item", "Cost",
"ID"), row.names = c(NA, -7L), class = "data.frame") | unknown | |
d12966 | train | HashSet is an unordered collection - its elements are not stored in any particular order. You can regard HashSet as a bag that contains items - the items are all in the bag, but not in any particular order.
If you want a Set that contains elements in a specific order, use an implementation of SortedSet, for example TreeSet, instead of HashSet.
TreeSet by default stores its elements in "natural order", if you want a different order you can use the TreeSet constructor that takes a Comparator; supply your own Comparator that defines the order you want the elements to be sorted in.
A: The easiest was is to use a Comparator. You will need to implement the Comparable interface in your objects to tell them how dates relate to each other. See Telling HashSet how to sort the data for a concrete answer to your question.
A: You should use the implmentation LinkedHashSet to keep the order of insertion
replace
Set<String> set = new HashSet<String>();
with
Set<String> set = new LinkedHashSet<String>();
Better yet, use a TreeSet with a custom Comparator and sort the entries while adding them right away. | unknown | |
d12967 | train | Yes, an implementation is allowed to omit the copy/move construction of a class
object when certain criteria are met, it's called copy elision.
Under the following circumstances, the compilers are permitted to omit
the copy- and move-constructors of class objects even if copy/move
constructor and the destructor have observable side-effects.
And for your code,
If a function returns a class type by value, and the return
statement's expression is the name of a non-volatile object with
automatic storage duration, which isn't the function parameter, or a
catch clause parameter, and which has the same type (ignoring
top-level cv-qualification) as the return type of the function, then
copy/move is omitted. When that local object is constructed, it is
constructed directly in the storage where the function's return value
would otherwise be moved or copied to. This variant of copy elision is
known as NRVO, "named return value optimization".
Note that the copy/move ctor still need to be accessible.
Even when copy elision takes place and the copy-/move-constructor is not called, it must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed. | unknown | |
d12968 | train | You don't need Task to load image asynchronously. You can use Unity's UnityWebRequest and DownloadHandlerTexture API to load. The UnityWebRequestTexture.GetTexture simplifies this since it setups up DownloadHandlerTexture for you automatically. This is done in another thread under the hood but you use coroutine to control it.
public RawImage image;
void Start()
{
StartCoroutine(LoadTexture());
}
IEnumerator LoadTexture()
{
string filePath = "";//.....
UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(filePath);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
Texture texture = ((DownloadHandlerTexture)uwr.downloadHandler).texture;
image.texture = texture;
}
}
You can also load the file in another Thread with the Thread API. Even better, use the ThreadPool API. Any of them should work. Once you load the image byte array, to load the byte array into Texture2D, you must do it in the main Thread since you can't use Unity's API in the main Thread.
To use Unity's API from another Thread when you are done loading the image bytes, you would need a wrapper to do so. The example below is done with C# ThreadPool and my UnityThread API that simplifies using Unity's API from another thread. You can grab UnityThread from here.
public RawImage image;
void Awake()
{
//Enable Callback on the main Thread
UnityThread.initUnityThread();
}
void ReadImageAsync()
{
string filePath = "";//.....
//Use ThreadPool to avoid freezing
ThreadPool.QueueUserWorkItem(delegate
{
bool success = false;
byte[] imageBytes;
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true);
try
{
int length = (int)fileStream.Length;
imageBytes = new byte[length];
int count;
int sum = 0;
// read until Read method returns 0
while ((count = fileStream.Read(imageBytes, sum, length - sum)) > 0)
sum += count;
success = true;
}
finally
{
fileStream.Close();
}
//Create Texture2D from the imageBytes in the main Thread if file was read successfully
if (success)
{
UnityThread.executeInUpdate(() =>
{
Texture2D tex = new Texture2D(2, 2);
tex.LoadImage(imageBytes);
});
}
});
} | unknown | |
d12969 | train | If I think about it k[0][0] in my mind means get me the first element of the dictionary then the first sub element.
No, k is the key of a given key-value pair. You are iterating over the items, which are those pairs:
for k,v in Team.items():
Each key-value pair is assigned to the names k and v there.
Given that you have two different types of keys in your dictionary, strings and tuples, your type() information shows you exactly that; you print a series of <class 'str'> and <class 'type'> for those keys.
So if k is a tuple, then k[0] is the first element in that tuple and k[0][0] is the first character of that first element:
>>> k = ('projectmanager', 'Asma')
>>> type(k)
<class 'tuple'>
>>> k[0]
'projectmanager'
>>> k[0][0]
'p'
For strings, k[0] would be the first character. But a single character is a string too. A string of length 1, so getting the first element of that string is still a string, again of length 1:
>>> k = 'developer1'
>>> type(k)
<class 'str'>
>>> k[0]
'd'
>>> type(k[0])
<class 'str'>
>>> len(k[0])
1
>>> k[0][0]
'd'
You wouldn't get an empty value here.
A: Consider,
First case- key, k is set to be a to be tuple. For instance ('projectmanager','Asma'). Hence obviously k[0][0] will print out p
Second case (the more tricky one) when k is set to be a string, k[0] is the first element of string. k[0] is hence a string of length 1. Doing
k[0][0] would access the first element of k[0] which is inturn the same as k[0] is a string of length 1.For example when k is 'developer1' ,k[0] is'd' and k[0][0] is hence 'd'
Hope this helps, good luck | unknown | |
d12970 | train | You can add location information to your image like this
let locationCordinate = CLLocationCoordinate2DMake(lat, long)
let currentDate = NSDate()
let imageLocation = CLLocation(coordinate: locationCordinate, altitude: 0.0, horizontalAccuracy: 0.0, verticalAccuracy: 0.0, timestamp: currentDate)
After this you can add this location to your image like this
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetLocationChangeRequest = PHAssetChangeRequest(forAsset: lastImageAsset)
assetLocationChangeRequest.location = imageLocation
}, completionHandler: {
(success:Bool, error:NSError?) -> Void in
if (success) {
print("Succesfully saved location to image")
} else {
print("Failed to save with Error : \(error!)")
}
}) | unknown | |
d12971 | train | First, you have to understand a few very important things:
Garbage Collection happens randomly.
Secondly,
Only those objects that have no variables referring to them are eligible for GC
Thirdly,
f= new int[NX,NY];
You are making f refer to something else. The original f is still referenced by the Form1.f. But this new int[NX, NY] object is now created and referred to only by the local f in the method.
After the method returns, nothing should be referring to the new f (unless you assigned it to somewhere else), so the new f becomes eligible for GC. Note that I said "becomes eligible for GC" instead of "is garbage collected".
However, since Form1 is still holding a reference to the original f, the original f will not become eligible for GC before the form does (unless you set it to something else). | unknown | |
d12972 | train | These are the following things you need to do to setup Apache for Django. I assume you are using Python 2.7 (32-bit) on Windows (32-bit) with WAMP server (32-bits) installed.
*
*Download mod_wsgi-win32-ap22py27-3.3.so. Or download your respective .so compatible file
*Change its name to mod_wsgi.so and copy it to /Program Files/Apache Software Foundation/Apache22/modules on Windows.
*Open httpd.conf using Admin rights. Now, you will find a list of lines with LoadModule .... Just add LoadModule wsgi_module modules/mod_wsgi.so to that list.
Your are partially done.. you can restart the apache and shouldn't find any errors.
*Now you need to link it to your Django project.
*In your Django project root folder, add apache folder and create django.wsgi (don't change this name) and apache_mydjango.conf.
*In httpd.conf add the following line at the bottom of the page.
Include "d:/projects/mysite/apache_django_wsgi.conf"
Open django.wsgi and add the following lines:
import os, sys
sys.path.append('d:/projects/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Open apache_djang_wsgi.conf and add:
Alias /images/ "d:/projects/mysite/templates/images/"
<Directory "d:/projects/mysite/images>
Order allow,deny
Allow from all
</Directory>
WSGIScriptAlias / "d:/projects/mysite/apache/django.wsgi"
<Directory "d:/projects/mysite/apache">
Allow from all
</Directory>
<VirtualHost *:80>
DocumentRoot d:/projects/mysite
ServerName 127.0.0.1
</VirtualHost>
Note:
I am assuming your Django project hierarchy is something like this:
mysite/
mysite/
settings.py
urls.py, wsgi.py.
manage.py
<apache> / apache_django_wsgi.conf, django.wsgi
Best tutorial links:
*
*port25.technet.com | Published my microsoft.
*mod_wsgi Quick Install guide
*Django site
*Django site
Actually I don't understand why people are unable to fix it. I've seen lots of questions on it here and I even posted few...So, I thought to write a initial setup version directly as answer
A: Try the following websites for the unofficial windows binaries for python extensions
http://www.kaij.org/blog/?p=123
https://github.com/kirang89/pycrumbs/pull/28
A: Just in case anyone is using this and doesn't spot it, there is an inconsistency in the steps. In Step 5 it refers to the filename apache_mydjango.conf
In Step 6 it refers to the filename apache_django_wsgi.conf
These should obviously both be the same name - it doesn't matter which way round you go for - but I spent a while trying to figure out why it wasn't working.
A: Apart from Olly's correction, there is another error in Step6:
Instead of
Include "d:/projects/mysite/apache_django_wsgi.conf"
it should be
Include "d:/projects/mysite/apache/apache_django_wsgi.conf"
I made all the steps and now can't start Apache Server anymore. The Wamp Image is red. I could restart Apache as described in Step 3.
A: How I configured Apache + Django + venv
For it to work you need 3 things:
*
*install mod_wsgi on python and apache
*setup httpd.conf on apache
*configure python script (usually wsgi.py) that is loaded by mod_wsgi and in turn loads your python app
1. Is described well enough in the official doc (I used the pip method). Just unpack apache distro (ApacheHaus worked for me, but not Apache Lounge, it missed some headers I think) to a standard place like C:\ or set env var MOD_WSGI_APACHE_ROOTDIR to its dir. You'll need Visual Studio Build Tools or binary distribution of mod_wsgi. Then pip install it.
2. In httpd.conf add:
LoadFile ".../pythonXY/pythonXY.dll"
LoadModule wsgi_module ".../mod_wsgi/server/mod_wsgi.cpXY-win_amd64.pyd"
WSGIPythonHome ".../pythonXY"
WSGIScriptAlias / "...\wsgi.py"
Here LoadFile may be necessary if Python isn't installed the standard way. Better to include.
WSGIPythonHome directive should point to main python distro (not venv as is usually said), because mod_wsgi may be somewhat not working properly. For instance now WSGIPythonPath is doing nothing at all. Alternatively, you can set PYTHONPATH or PYTHONHOME env vars accordingly.
Now you can monitor error log of apache (inside its log folder by default).
In case of failures apache will print mod_wsgi configuration (meaning it is installed, but couldn't start python) and/or python errors if it managed to start.
3. Inside your python script (wsgy.py) you'll need to provide function "application" (so is mod_wsgi usually compiled) which starts your app. But first point python to the modules and packages it will use, your own as well, right in the script with sys.path or site.addsitedir. Django's wsgi.py is good, just prepend all path conf there.
A: Only for users running windows 64 versions.
I have created wsgi. Now you only need to install python and run apache.
The configurations have already been set in the package. Just download the package and follow the instructions from 'Steps to follow.txt file' present in package.
You dont need to download python and apache and mod_wsgi.so from anywhere. I have compiled the so file, and compatible python and apache2 versions. So that you are ready to deploy.
Just that in apache config the document root has been set to cgi-bin folder present inside Apache2.
Package can be downloaded from Zip package
Instructions and package usage | unknown | |
d12973 | train | You cannot access the call log using the SDK and approved APIs. There are some workarounds, as you probably already know. The only option I know about is accessing call_history.db.
Take a look at this tutorial. Unfortunately for you, security has been made more severe, and you only can access that file in iOS < 5.0 (and probably all jailbreacked versions). | unknown | |
d12974 | train | As far as I'm aware, there is no limit, but if you want to be sure, you should ask either the GitHub support team or on the GitHub community forums.
GitHub itself has such a bot account and PATs are frequently used there, but do be aware that the UI may be a little (or, depending on how many tokens you issue, very) slow, since it isn't designed for people to have huge numbers of PATs.
You may find it more desirable to use deploy keys if you're accessing a repo, since these have a smaller scope (one repository) and won't have the UI problems mentioned above, but of course that won't work for the API. | unknown | |
d12975 | train | setupController isn't needed (it's doing the exact same job as the model hook in your route, after the model hook as already done it's work. Delete it.
As for your issue, I don't think Ember.Controller proxies model properties. You'd need to use Ember.ObjectController to do that, but seeing as Ember.ObjectController is on Tom Dale's hit list (it's going away eventually), really you should access stackTitle in your templates as model.stackTitle. | unknown | |
d12976 | train | I also tried with not result :
<script>
jQuery(document).ready(function(){
$('html:lang(fr-FR) .fa-facebook').attr('href', 'https://myfacebookpage.com'); }); </script>
A: Basically what you should do is check the language of the <html> tag on document ready and after loop through all the facebook links and update their href. Something like this:
$(document).ready(function() {
const documentLanguage = $("html").attr("lang");
const facebookLinks = $(".fa-facebook");
facebookLinks.each(function(index, link) {
if (documentLanguage === "fr-FR") {
$(link).parent().attr("href", "https://facebook.com/my-french-site/");
} else if (documentLanguage === "en-EN") {
$(link).parent().attr("href", "https://facebook.com/my-english-site/");
}
});
});
Here is a live sample: https://jsfiddle.net/rhernando/kwndv609/3
EDIT
I forgot about the tree structure of your DOM the class element is an <i> tag so you have to point to it's parent element. The updated code should work.
A: you have a typo in the attribute selector:
| should be before =, not after:
$('html[lang|=fr] .fa-facebook')
More about attribute selectors here: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors | unknown | |
d12977 | train | Try this:
echo "replenishment_category string,Date string" | sed "s/$PARTITION_COLUMN.*//"
Notice the space removed after .* and the double quote around the entire command.
A: Since you want to remove variable as well as comma before it so following sed may help you here.
echo "replenishment_category string,Date string" | sed "s/,$PARTITION_COLUMN.*//g"
A: sed would obviously work here:
echo "replenishment_category string,Date string" | sed "s/\b,$PARTITION_COLUMN.*//"
Output:
replenishment_category string
A: You could do this with shell parameter expansion alone, assuming you have extended globs enabled (shopt -s extglob):
$ var='replenishment_category string,Date string'
$ part_column=Date
$ echo "${var%%?(,)"$part_column"*}"
replenishment_category string
*
*The ${word%%pattern} expansion works without extended globs and removes the longest match of pattern from the end of $word.
*The ?(pattern) extended pattern matches zero or one occurrences of pattern and is used to remove the comma if present.
*"$part_column"* matches any string that begins with the expansion of $part_column. Quoting it is not required in the example, but good practice to prevent glob characters from expanding. | unknown | |
d12978 | train | JS does align with the ECMAScript spec. null values may have a Null type, but that does not mean that typeof is supposed to return "null". You can see the spec behavior in section 12.5.5.1, which defines the runtime behavior of typeof, that Null-type objects return "object" from typeof. | unknown | |
d12979 | train | @Chris G has already covered this in their comments, but I wanted to explore what's happening with you in greater depth.
Here's the code you have, in plain English:
function countDone:
create variable "numberOfDone" and set to 0
iterate over all todos. for each todo:
if the todo is done:
increase variable "numberOfDone" by 1
return variable numberOfDone
end iteration
end function
Spot the error? Check out the indentation. Spoiler: The function isn't returning anything.
You're returning numberOfDone every iteration of the for loop rather than right at the end of the function like you want.
Returning a value at the wrong point in a function is an incredibly common programming error – I'd bet every programmer has faced this at one point. That's something that you should think about going forward: checking if a function returns anything is an excellent starting place when debugging functions.
Anyway, cheers, and welcome to Stack Overflow! Congrats on your first question! | unknown | |
d12980 | train | Well after what felt like a wild goose hunt I found this little gem in an open issue on the geckodriver github page. I have confirmed that this has fixed my issue and now I am able to create an instance of firefox driver and successfully open Firefox 47. https://github.com/mozilla/geckodriver/issues/91
Here is a snippet of the code from the above URL in case the link goes dead
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();
service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
IWebDriver driver = new FirefoxDriver(service);
Hope this helps others. But there is a bug which is currently a blocking issue for all my tests. All of my tests access our internal test environments which have self signed certs and there is a bug with marionette where you cannot handle these.
https://bugzilla.mozilla.org/show_bug.cgi?id=1103196
=( | unknown | |
d12981 | train | Probably type class is something you are looking for? Consider this example
trait Companion[T] {
val comp: T
}
object Companion {
def apply[T: Companion] = implicitly[Companion[T]]
}
object UnrelatedType {
implicit val thisComp =
new Companion[UnrelatedType.type] {
val comp = UnrelatedType
}
}
// Somewhere later
type Unrelated = UnrelatedType
implicit val unrelated = Companion[UnrelatedType] | unknown | |
d12982 | train | Add the % in the input field using pipe
first create the formcontrolname and bind the value in the input text
<input type="text" formControlName="amount" [value]="myform.get('controlname')|pipe">
i attached the stackbliz,kindly refer it | unknown | |
d12983 | train | The (signed) angle is always end - start. Assuming the start and end angles are both in the same range [n, n + 360), their difference will be between (-360, 360).
To normalize the difference to a positive angle in the range [0, 360), use:
tAngle = (tEndBearing - tStartBearing + 360) % 360;
To normalize the difference to a signed angle in the range [-180, 180), instead, use:
tAngle = (tEndBearing - tStartBearing + 360 + 180) % 360 - 180;
The above work whether the start angle is smaller than the end one, or the other way around. | unknown | |
d12984 | train | *
*char arr1D [5 * 10]; - is zero initialized.
*((arr2D)arr1D)[0] - reinterprets the memory pointed to by arr1D as a pointer to char*. This has an unspecified address (zero byte pattern isn't necessarily the NULL address).
*((arr2D)arr1D)[0][0] - derefrences that unspecified address. Undefined behavior.
Your naming also suggests a misconception common about pointers and arrays. Arrays aren't pointers. And pointers aren't arrays.
Arrays decay into pointers to the first element.
char[2][2] is a 2D char array that will decay to char(*)[2] (a pointer to an array).
char** is not a 2D char array, it's a pointer to a pointer. | unknown | |
d12985 | train | You are probably compiling AppDelegate into your test target. Don't do this.
Instead, only compile into your normal app target MyAppName. In you test class write in XCode 7
@testable import MyAppName
and before XCode 7
import MyAppName | unknown | |
d12986 | train | Use this code...
if([thearray containsObject:[NSNumber numberWithInt:indexPath.row]]) {
//perform action here
}
A: I think the best you can do here is check if the current count of the array is greater than indexPath.row the (since in theory there will be no gaps in the indexes). The method you are currently calling takes an object and tells you if it is a member of the array. There is also objectAtIndex:, but that raises an exception if the integer you pass is out of bounds.
if(thearray.count > indexPath.row) {
// array has at least indexPath.row + 1 items, so you can get objectAtIndex:indexPath.row
} | unknown | |
d12987 | train | def 1st_funtion(a_matrixA)
#apply some rule on a_matrixA and return a new matrix(next state of the cell)
return new_matrix
def 2nd_funtion(a_matrixB,repeat_times)
for i in range(repeat_times):
a_matrixB = 1st_funtion(a_matrixB)
return a_matrixB | unknown | |
d12988 | train | "I want the resulting html from this php file to be loaded into the div tag"
Well, that's exactly what .load does:
$('#target').load('http://www.example.com/page.php');
Loads the content of http://www.example.com/page.php into the element named target.
If this isn't working, you need to be clearer on what the problem is.
A: So based on the discussions, it appears that it is NOT possible to load a php file that contains a mix of php, html, and javascript document.write in it and put that within a div tag in another file dynamically.
What IS possible, at least the only solution I have found thus far, is to include the php file with other php code and html and even a script tag but NO document.write in it.
To add the customizations I had in the document.write javascript, I instead used the following example to send the javascript variables to the php file, have it process it as a php variable and send back the full file. (Based on: Jquery load() and PHP variables )
$('#mainContent').load( "another.php",
{
'key1': js_array['key'],
'key2': js_variable_value
}
);
Then the parameters are posted to the file test.php and are accessible as:
<?php
$key1 = $_POST['key1']
$key2 = $_POST['key2']
?>
// some html code
...
<img alt="photograph" src="<?php echo $key1; ?>" />
Would love to know a better solution. | unknown | |
d12989 | train | You can do this if the user is using HTTPS. You'd need to use the authenticated user endpoint to find the user ID of the current user, say, using curl, and then see if that user is the same as the owner of the repository by checking the URL.
To get the appropriate credentials, you can take the remote URL (e.g., https://github.com/git/git.git) and pipe it to git credential fill to find the username and password, like so:
echo url=https://github.com/git/git.git | git credential fill
The output format is defined in the git-credential man page. These credentials should also be able to be used for the API to make your request, although note that since curl requires the password to be passed on the command line, you will expose those credentials to anyone else on the machine. A non-shell option may be a more security-conscious choice.
Technically, there are also ways to determine this via SSH, but those rely on parsing fixed output that is subject to change, and as such, you should assume that you cannot get that information for SSH remotes.
Note that this tells you the current user, which you can check against the URL, but it doesn't tell you whether the user has administrative privileges on a repo that they don't own themselves (such as one owned by an organization). Since you haven't told us what you want to do with this information, we can't help you out there, although if you're trying to use the API, you can just do it and see if it succeeds or not.
Since you are using the user's credential store in this case, you need to be explicit and up front with the user about what you're doing so that the user isn't surprised by your use of the credentials. It would be unethical and probably illegal to use the user's credentials in the way I've described without their knowledge and consent. | unknown | |
d12990 | train | Because of the threading requirements of the WebView, I don't think that you can achieve what you want I'm afraid. The only way to start a new javascript execution in Java from the background thread would be to post a task back to the UI thread, but that break your synchronous needs.
I think your only option is to have the Java object return a String back to your JavaScript and then eval it (as you are suggesting, I think).
A: You could modify your JavaScriptTest interface to return the javascript you want to evaluate.
public class JavaScriptTest
{
public String foo()
{
return "bar();"
}
public void bar()
{
Log.d("Test", "bar");
}
}
Then in your javascript:
function Test()
{
};
Test.prototype.foo = function()
{
eval(window._test.foo());
};
Test.prototype.bar = function()
{
window._test.bar();
};
var test = new Test();
You wouldn't have bar() evaluated before returning but you could do it immediately afterwards. | unknown | |
d12991 | train | Mostly I doubt it has to do with the permission you need to give while running the app. Are you making sure you are setting the the network permission in manifest?
More information or code could help you get better answers though. | unknown | |
d12992 | train | Use isinf to detect Inf, and use the output as a logical index into your array:
data(isinf(data)) = 1; | unknown | |
d12993 | train | You can try the default way of creating a venv. For more information look here
python3 -m venv tutorial-env
and activate it with
source/tutorial-env/bin/activate | unknown | |
d12994 | train | you might build the SKSpriteNode in this way:
func makeCircle(width:CGFloat = 200, height:CGFloat = 200) -> SKSpriteNode? {
let size = CGSize(width: width, height: height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
StyleKit.drawCircle(frame: CGRect(origin: .zero, size: size), resizing: .AspectFit)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let safeImage = image {
return SKSpriteNode(texture: SKTexture(image: safeImage))
} else {
return nil
}
} | unknown | |
d12995 | train | Just create an outlet to your textField, add the UITextViewDelegate and set the delegate. After that just override the textViewDidChange method. Code example below
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
@IBAction func textField_EditingChanged(sender: UITextField) {
// Will print out each letter that is typed
print(sender.text!.characters.last!)
// Will print out the word
print(sender.text!)
}
func textViewDidChange(textView: UITextView) {
// Will print out each letter that is typed
print(textView.text!.characters.last!)
// Will print out the word
print(textView.text!)
} | unknown | |
d12996 | train | I would first check to see if the events are working when adding eventlisteners. There must be a way to handle key events on Android:
<textarea id="mytextarea"></textarea>
let mytextarea = document.getElementById('mytextarea');
mytextarea.addEventListener('keydown', (event) => {
console.log(event.code);
});
If this is not working; you asked for a hack or trick: try the focus and blur events, then you could run a function on interval that clears the textarea. Note that this blocking trick is something that goes against good user experience conventions, so should be considered a hack/trick for sure ;-)
<textarea id="mytextarea"></textarea>
let int1;
let mytextarea = document.getElementById('mytextarea');
mytextarea.addEventListener('focus', () => {
clearInterval(int1);
int1 = setInterval(() => {
mytextarea.value = '';
}, 10)
});
mytextarea.addEventListener('blur', () => {
clearInterval(int1);
});
A: Instead of using event.key or event.code properties of keypress (keyup, keydown) event, I have used event.inputType, event.data of update event and added few restricting attributes to the input tag to overcome 'smartness' of mobile keyboard app. It is an ugly hack but worked for my purpose.
HTML:
<textarea id="inpt" autocapitalize="none" autocomplete="off" autocorrect="off" spellcheck="false" ></textarea>
</div>
JS:
var inpt = document.getElementById('inpt');
inpt.addEventListener('input', do_on_input);
function do_on_input(e) {
if( e.inputType == "insertText"){
console.log( e.data );
}
if( e.inputType == "deleteContentBackward"){
console.log('Backspace');
}
if( e.inputType == "insertCompositionText"){
// without restrictive attribbutes you will need to deal with this type events
}
} | unknown | |
d12997 | train | Your code is pretty bad for several reasons. Instead of trying to fix them, which would leave you with a bad-but-working code, I'm going to point them out, and suggest a better way.
*
*You first while(my $row = <$fi>) iterates over the whole file when you are only interested in the first two rows. You should just use <$fi> twice to read the first two lines:
my $headers = <$fi>;
my $filters = <$fi>;
*You shouldn't duplicate code. In particular, you wrote twice
chomp($row);
$row=~ s/\A\s+//g;
$row=~s/\R//g;
Whereas you could have put that only once at the beginning of the while.
*Same thing for $trace++: you want it done at every iteration of your foreach loop; there is no reason to put it in at the end of the if and at the end of the else.
*always use strict and use warnings.
Here is what I suggest instead:
use strict; # Always use strict and warnings!
use warnings;
my $iniFilename = "Sample.csv";
open(my $fi,'<',$iniFilename) or die "Can't open $iniFilename";
my @headers = split ',', <$fi> =~ s/\A\s+|\s+\Z//gr, -1;
my @filter = split ',', <$fi> =~ s/\A\s+|\s+\Z//gr, -1;
for my $i (0 .. $#filter) {
$headers[$i] = undef if !$filter[$i] || $filter[$i] eq "" ;
}
# @headers now contains (undef, "Memory", undef, "Extra 1", "Extra 2")
If you need the index of @headers that are not undef:
my @headers_indices = grep { defined $headers[$_] } 0 .. $#headers;
If you need just the names of the non-undef headers:
my @non_undef_headers = grep { defined $_ } @headers;
Finally, since you are parsing CSV files, you might want to use a CSV parser (Text::CSV_XS for example), rather than split /,/. (the latter will misbehave with quoted fields containing commas or newlines (and probably has other issues that I'm not thinking about right now)) | unknown | |
d12998 | train | There is no MEDIAN() function in MySQL but there is a somewhat simple way to calculate it as demonstrated on this website:
https://www.eversql.com/how-to-calculate-median-value-in-mysql-using-a-simple-sql-query/
Assuming your table is named salaries:
SET @rowindex := -1;
SELECT
AVG(salary)
FROM
(SELECT @rowindex:=@rowindex + 1 AS rowindex,
salaries.salary AS salary
FROM salaries
ORDER BY salaries.salary) AS s
WHERE
s.rowindex IN (FLOOR(@rowindex / 2) , CEIL(@rowindex / 2));
Explanation:
*
*Let's start with the internal subquery - the subselect assigns @rowindex as an incremental index for each salary that is selected, and sorts the salaries.
*Once we have the sorted list of salaries, the outer query will fetch the middle items in the array. If the array contains an odd number of items, both values will be the single middle value.
*Then, the SELECT clause of the outer query returns the average of those two values as the median value.
A: select avg(Salary)
from
(
select *,
ROW_NUMBER() over (order by Salary desc) as desc_salary,
ROW_NUMBER() over (order by Salary asc) as asc_salary
from Table_Name
) as a
where asc_salary in (desc_salary,desc_salary+1, desc_salary-1) | unknown | |
d12999 | train | The bug is at
$pr_val = array_keys($massiv);
echo "<td>".$pr_val[0]. "</td>";
array_key($massiv) returns all keys of massiv and $pr_val[0]always returns the first of them (which happens to be the smallest of them).
Try
foreach($product as $good =>$massiv) {
foreach($massiv as $inner_key =>$price) {
echo "<tr><td>". $good. "</td>";
echo "<td>".$inner_key. "</td>";
echo "<td>".$price."</td></tr>\r\n"; // product price
}
}
That should output exactly what you desire.
A: This code will output what you desire as the correct output in an HTML table
$array[1]=array("Name1"=> array("2"=>"1460","3"=>"1868","4"=>"2158","5"=>"2537","6"=>"2915","8"=>"3673"));
$array[2] =array("Prod2"=> array("3"=>"3079","4"=>"3625","5"=>"4172","6"=>"4718","8"=>"5811"));
echo "<table>" . PHP_EOL;
foreach($array as $product) {
foreach($product as $name =>$massiv) {
foreach($massiv as $inner_key => $price) {
echo "<tr><td>". $name. "</td>";
echo "<td>".$inner_key. "</td>";
echo "<td>".$price."</td></tr>" . PHP_EOL; // product price
}
}
}
echo "</table>" . PHP_EOL;
A: $array = array();
$array[0] = array("Name1"=> array("2"=>"1460","3"=>"1868","4"=>"2158","5"=>"2537","6"=>"2915","8"=>"3673"));
$array[1] = array("Prod2"=> array("3"=>"3079","4"=>"3625","5"=>"4172","6"=>"4718","8"=>"5811"));
echo '<table rules="all" border="1">';
foreach($array as $v) {
foreach($v as $name => $ar) {
foreach($ar as $v1 => $v2) {
echo sprintf('<tr><td>%s</td><td>%s</td><td>%s</td></tr>'."\r\n",
$name, $v1, $v2);
}
}
}
echo '</table>';
by Prizma | unknown | |
d13000 | train | You can't do this kind of filtering via the Smartsheet API exactly. One approach would be you could do a GET Sheet request and use the columnIds query string parameter to provide the id number of the specific column you are looking to review. Then you would get back a response that only contained data for that specific column. The filtering based on the date values would then have to be done by you in your code.
If you will need other data in the rows I would then just do the GET Sheet request to get all of the data in the sheet and do the filtering of the response in your code. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.