text:
Q: Is it possible to test for support for ::marker content using @supports? I wanted to make a nested ordered list with a specific numbering system, like so:
https://www.stairball.club/stairball-rules/
Here's the relevant CSS I'm using:
/* Numbering for nested rule lists */
.rule-list ol {
    counter-reset: rules;
}
.rule-list li {
    counter-increment: rules;
    font-weight: bold;
}
.rule-list li li {
    font-weight: initial;
}

.rule-list li::marker {
    content: counters(rules, '.') '. ';
    font-weight: bold;
}
/* Don't apply to Webkit which doesn't support ::marker content */
@supports (-webkit-hyphens: auto) {
    .rule-list li {
        list-style: none;
    }
    .rule-list li::before {
        content: counters(rules, '.') '. ';
        color: #E77B95;
        font-weight: bold;
        margin-left: -2em;
    }
}

I based my code on this lovely article, Styling Ordered Lists with CSS Counters.
Replacing the li marker with the numbering system I want to use was straightforward in Chrome and Firefox, but Safari refuses to do the replacement: https://github.com/mdn/content/issues/984
Safari/WebKit supports the ::marker pseudo-element, but not the content property. So I need to fall back to using the ::before pseudoelement, but this is apparently bad for accessibility, and it also looks bad because I'm not able to get the indentation right. The numbers do not appear where a marker would appear, they appear in the text itself. I'm currently giving them a negative margin to move the numbers to the left, but this isn't adequate beyond the first level of nesting.
Right now I am testing whether the browser is WebKit with @supports, by checking whether the browser supports -webkit-hyphens, which I know only WebKit supports. This is not ideal, however, because if WebKit fixes support for the content property in the future, new WebKit browers won't automatically start using my preferred code. I won't be able to differentiate between old broken WebKit and new fixed WebKit. Also, if there are other stupid browsers like WebKit, I won't be able to detect their brokenness.
Is there any way to test for support for the content property under a selector using the ::marker pseudo-element?

A: No it's not, the approach is to provide the marker and the fallback for older browsers it ... so what if it aint so pretty.


text:
Q: Clear formData after $.ajax submit var fd = new FormData();
fd.append( 'file', input.files[0] );
fd.name = 'something';
fd.etc = 'something more';

$.ajax({
  url: 'http://example.com/script.php',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

I put above code within a submit event, I found in my backend I received duplicated formData's data. Because after submit I did not want to hard refresh the page for good UX. How to clear the formData after ajax's success?

redpajama_set_name: RedPajamaStackExchange


text:
Q: timeout/memory leak with Phonegap/Cordova I'm writing an app using Cordova/Phonegap 2.2.0
Its running on an LG Ally (Android 2.2.2)
The app retrieves a rather large amount of data from a web server and in the process the app prematurely ends.  I say that instead of errors out because I don't get the typical Android "Application stopped responding" dialog.  Instead, the app exits and and returns to the home screen.
The log shows the following message:
D/DroidGap(4018): Paused the application!
D/CordovaWebView(4018): Handle the pause
W/dalvikvm(4018): ReferenceTable overflow (max=512)
W/dalvikvm(4018): Last 10 entries in JNI local reference table:
W/dalvikvm(4018):   502: 0x44ae70c8 cls=Ljava/lang/String; (28 bytes)
W/dalvikvm(4018):   503: 0x44c93538 cls=Ljava/lang/String; (28 bytes)
W/dalvikvm(4018):   504: 0x44c76b70 cls=Ljava/lang/String; (28 bytes)
W/dalvikvm(4018):   505: 0x44a64810 cls=Ljava/lang/String; (28 bytes)
W/dalvikvm(4018):   506: 0x449ef708 cls=Ljava/lang/String; (28 bytes)
W/dalvikvm(4018):   507: 0x449d06b8 cls=Ljava/lang/String; (28 bytes)
W/dalvikvm(4018):   508: 0x449cd330 cls=Ljava/lang/String; (28 bytes)
W/dalvikvm(4018):   509: 0x449cc198 cls=Ljava/lang/String; (28 bytes)
W/dalvikvm(4018):   510: 0x449cb4c8 cls=Ljava/lang/String; (28 bytes)
W/dalvikvm(4018):   511: 0x449ea780 cls=Landroid/webkit/WebViewCore; (132 bytes)
W/dalvikvm(4018): JNI local reference table summary (512 entries):
W/dalvikvm(4018):   496 of Ljava/lang/String; 28B (496 unique)
W/dalvikvm(4018):    15 of Ljava/lang/String; 36B (15 unique)
W/dalvikvm(4018):     1 of Landroid/webkit/WebViewCore; 132B
W/dalvikvm(4018): Memory held directly by tracked refs is 14560 bytes
E/dalvikvm(4018): Failed adding to JNI local ref table (has 512 entries)
I/dalvikvm(4018): "WebViewCoreThread" prio=5 tid=8 RUNNABLE
I/dalvikvm(4018):   | group="main" sCount=0 dsCount=0 s=N obj=0x449ea828 self=0x1274c8
I/dalvikvm(4018):   | sysTid=4025 nice=0 sched=0/0 cgrp=unknown handle=1221400
I/dalvikvm(4018):   at android.webkit.WebViewCore.nativeHandleTouchEvent(Native Method)
I/dalvikvm(4018):   at android.webkit.WebViewCore.access$3400(WebViewCore.java:52)
I/dalvikvm(4018):   at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:1159)
I/dalvikvm(4018):   at android.os.Handler.dispatchMessage(Handler.java:99)
I/dalvikvm(4018):   at android.os.Looper.loop(Looper.java:123)
I/dalvikvm(4018):   at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:623)
I/dalvikvm(4018):   at java.lang.Thread.run(Thread.java:1096)
E/dalvikvm(4018): VM aborting

I'm unsure if this is a timeout problem or if I'm running the device out of memory or what's going on.
Any help would be greatly appreciated.
Mark

A: I found the Solution to this error. Move your resources (images, fonts,..) from your asset forlder to sdcard folder and te error is fixed !


text:
Q: I need to arrange this code in a way i can call it from anywhere I have this JavaScript function that runs immediately after the DOM loads. It tries to get the element of the drag-drop field although it is not yet available resulting to a null error. Therefore i am unable to use this function if my drag-drop is a modal or in any other page that does not load when the system starts.
My current solution is to load a hidden drag drop field but I need a more flexible solution where I can implement it from anywhere. I need to stop it from running immediately the website loads and trigger it through an event like on drop or on load in such a way it will run the whole of it. I have tried to rearrange it but the code is too messed up hence thought the original one would be easy for you to understand. I know jquery is easier but am in a situation where i need to use vanilla javascript
(function() {

  // getElementById
  function $id(id) {
    return document.getElementById(id);
  }

  // file drag hover
  function FileDragHover(e) {
    e.stopPropagation();
    e.preventDefault();
    e.target.className = (e.type == "dragover" ? "hover" : "");
  }

  // file selection
  function FileSelectHandler(e) {

    // cancel event and hover styling
    FileDragHover(e);

    // fetch FileList object
    var files = e.target.files || e.dataTransfer.files;

    // process all File objects
    for (var i = 0, f; f = files[i]; i++) {
      UploadFile(f);
    }

  }

  // output file information
  function ParseFile(file) {

    var iconpath = "";
    var size = 0;
    var units = "";

    if (file.type == "application/pdf") {
      iconpath = "";
    } else {
      iconpath = "File Information:";
    }

    if (file.size > 1048576) {
      size = file.size / 1024 / 1024;
      units = "MB";
    } else {
      size = file.size / 1024;
      units = "KB";
    }

    return "" + iconpath + "	" + file.name + "	" + file.type + "" + size.toFixed(2) + "" + units + "	";
  }

  // upload JPEG files
  function UploadFile(file) {

    // following line is not necessary: prevents running on SitePoint servers
    if (location.host.indexOf("sitepointstatic") >= 0)
      return

    var xhr = new XMLHttpRequest();
    if (xhr.upload) {

      // create progress bar
      var o = $id("messages");
      var k = $id("progress");
      var step = k.appendChild(document.createElement("z"));
      var content = o.appendChild(document.createElement("tr"));
      var progress = k.appendChild(document.createElement("p"));
      progress.appendChild(document.createTextNode("Waiting to upload"));
      // progress bar
      xhr.upload.addEventListener("progress",
        function(e) {
          var pc = parseInt(e.loaded / e.total * 100);
          progress.style.width = pc + "%";
          progress.innerHTML = pc + "% " + file.name;
          if (pc == 100) {
            content.innerHTML = ParseFile(file);
            k.removeChild(progress);
          } else {

          }
        },
        false
      );

      // file received/failed
      xhr.onreadystatechange = function(e) {
        if (xhr.readyState == 4) {
          progress.className = (xhr.status == 200 ? "success" : "failure");
        }
      };
      //make multipart
      var formData = new FormData();
      formData.append("thefile", file);

      // start upload
      xhr.open('POST', '/resources/dragdrop/upload.jsp?action=save', true);
      //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.onreadystatechange = function() {
        try {
          if (xhr.readyState == 4) {
            if (xhr.status == 200) {
              var respText = xhr.responseText.replace(/^\s+|\s+$/g, "");
              loadPageInDiv('resources/dragdrop', 'files.jsp', 'fileviewdiv')
            } else {
              alert("error hatujui");
            }
          }
        } catch (e) {
          alert(e);
        }
      };
      xhr.send(formData);
      ParseFile(file);
    }

  }

  // initialize
  function Init() {

    var fileselect = $id("fileselect"),
      filedrag = $id("filedrag"),
      submitbutton = $id("submitbutton");

    // file select
    fileselect.addEventListener("change", FileSelectHandler, false);

    // is XHR2 available?
    var xhr = new XMLHttpRequest();
    if (xhr.upload) {

      // file drop
      filedrag.addEventListener("dragover", FileDragHover, false);
      filedrag.addEventListener("dragleave", FileDragHover, false);
      filedrag.addEventListener("drop", FileSelectHandler, false);
      filedrag.style.display = "block";

      // remove submit button
      submitbutton.style.display = "none";
    }

  }

  // call initialization file
  if (window.File && window.FileList && window.FileReader) {
    Init();
  }

})();


text:
Q: I used $location.search to set paramValue, but if i select other link also it get appended to new url, how to solve it In Angularjs I used $location.search() to set paramValue in url i.e like
if i change dropdown executeSearch() will be called.
executeSearch()
{
  $location.search('type', Task);
}

result is : index.html#/search?type=Task.

but if i click on other link also it coming like
index.html#/help?type=Task

how to make it specific to this function only..if i click on other link also ?type=Task get appended. so how to remove this paramvalues("? folled by paramvalues") if i click on other links.
<select class="search-dropdown-select" ng-change="SearchBar.executeSearch()"
                        ng-model="SearchBar[item.model]"
                        ng-options="item.name for item in SearchBar.{{item.options}}"></select>

A: When clicking on the other link use $location.url().  This will clear all of the query parameters.
function navigate(path) {
  $location.url(path);
}

<a href ng-click="navigate('/help')">Help</a>


text:
Q: Keyboard closed on click on button in react native I have creating a comment modal in which user can add comment. This section has a list of comments and a text input field to enter comments and a button to submit comment but the problem is the I enter something in text input and then press button to submit comment but first time it closes the keyboard and then I need to press button again to add the text into the array.
My problem is why I need to press two times. Why on first time my keyboard got closed.
  <KeyboardAvoidingView
    style={{
      display: "flex",
      height: Dimensions.get("window").height,
      width: Dimensions.get("window").width,
    }}
    behavior={Platform.OS === "ios" ? "padding" : "height"}
  >
    <SafeAreaView
      style={{
        backgroundColor: "transparent",
        flex: 1,
      }}
    >
      <View
        style={{ flex: 0.4, backgroundColor: "#000", opacity: 0.2 }}
      ></View>

      <View
        style={{
          flex: 0.6,
          backgroundColor: Colors.dark.text,
          borderRadius: 20,
        }}
      >
        <View
          style={{
            flexDirection: "row",
            marginTop: "3%",
            paddingVertical: height * 0.005,
            marginVertical: "4%",
            borderTopRightRadius: 10,
            borderTopLeftRadius: 10,
            paddingHorizontal: "3%",
          }}
        >
          <View style={{ flexDirection: "column", width: width * 0.8 }}>
            <Text
              style={{
                fontFamily: "Roboto_700Bold",
                fontSize: 10,
                color: Colors.light.text,
                opacity: 0.4,
              }}
            >
              COMMENTS
            </Text>

            <Text
              style={{
                fontFamily: "Roboto_700Bold",
                fontSize: 20,
                marginTop: height * 0.01,
              }}
            >
              {title}
            </Text>
          </View>

          <TouchableOpacity
            onPress={() => setCommentVisible(false)}
            style={{
              width: width * 0.15,
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <SvgRedCross />
          </TouchableOpacity>
        </View>

        <View
          style={{
            flex: 0.002,
            backgroundColor: Colors.light.postText,
            opacity: 0.2,
          }}
        >
          <Text></Text>
        </View>

        <View style={{ flex: 0.87 }}>
          <FlatList
            data={allComment}
            showsVerticalScrollIndicator={false}
            keyExtractor={(item, index) => item.id}
            key={(item, index) => item.qId}
            renderItem={({ item, index }) => (
              <View>
                <View style={{ flexDirection: "column", padding: "3%" }}>
                  <Text
                    style={{
                      color: "#151617",
                      fontFamily: "Roboto_700Bold",
                      fontSize: 14,
                    }}
                  >
                    {item.name}{" "}
                  </Text>
                  <Text
                    style={{
                      color: "#151617",
                      fontFamily: "Roboto_400Regular",
                      fontSize: 13,
                    }}
                  >
                    {item.comment}{" "}
                  </Text>
                </View>

                <View
                  style={{
                    height: 0.5,
                    backgroundColor: Colors.light.postText,
                    opacity: 0.2,

                    marginTop: "3%",
                  }}
                >
                  <Text></Text>
                </View>
              </View>
            )}
            style={{}}
            pagingEnabled={false}
            showsHorizontalScrollIndicator={false}
          />
        </View>

        <View
          style={{
            height: height * 0.08,
            elevation: 2,
            backgroundColor: "#fff",
            flexDirection: "row",
            alignItems: "center",
            borderColor: Colors.light.tabSelection,
            shadowColor: Colors.light.tabSelection,
            shadowOffset: {
              width: 0,
              height: -3,
            },
            shadowRadius: 1,
            shadowOpacity: 0.4,
            position: "absolute",
            bottom: 0,
            flex: 0.2,
          }}
        >
          <TextInput
            style={{
              fontWeight: "300",
              fontStyle: "normal",
              fontSize: 13,
              fontFamily: "Roboto_400Regular",
              paddingLeft: "5%",
              paddingLeft: "5%",
              color:
                theme === true
                  ? Colors.dark.postDateText
                  : Colors.light.postDateText,
              width: "80%",
            }}
            value={comment}
            onChangeText={(value) => {
              setComment(value);
            }}
            maxLength={150}
            clearButtonMode="always"
            multiline={true}
            placeholder="Write your comments here..."
            placeholderTextColor={Colors.light.postDateText}
            onSubmitEditing={() => Keyboard.dismiss()}
          />

          //button code to submit comment
          <TouchableOpacity
            onPress={() => {
              addComment(comment);
              // Keyboard.dismiss();
            }}
            style={{ width: "20%", marginLeft: 10 }}
          >
            <SvgCommentArrow />
          </TouchableOpacity>
        </View>
      </View>
    </SafeAreaView>
  </KeyboardAvoidingView>

A: It may happened due to not specifying the keyboard type in the textinput props https://reactnative.dev/docs/textinput#keyboardtype.
also refer this
https://reactnative.dev/docs/keyboard


text:
Q: programmatically print out cell and comments contents from spreadsheet I have a spreadsheet with worksheets (originally in Google Sheets, but I can export to .xlsx or .ods) and I would like to programmatically print out the cell values of the first line along with the comments in each cell. E.g. see screenshot below of worksheet (https://docs.google.com/spreadsheets/d/1DGsrEKrxfQm8sRzfLyqu4z6Hx8eDdkVDiYlN3Rwve6A/edit?usp=sharing):

There are 3 cells in row1 each with a comment in them.
I would like to programmatically print out the contents of this worksheet so that they look something like:
Cell:"field1",Comment:"key=foobar"
Cell:"field2",Comment:"key=bar"
Cell:"field3",Comment:"key=foobar"

Any ideas?

A: google-spreadsheets
function getNotes_(fileId, sheetName, rangeA1)
{
  var data = [];
  var file = SpreadsheetApp.openById(fileId);
  var sheet = file.getSheetByName(sheetName);
  var range = sheet.getRange(rangeA1);
  var values = range.getValues();
  var notes = range.getNotes();
  var getResult_ = function(value, i) { data.push( 'Cell:"' + value + '",Comment:"' + rowNotes[i] +'"') };
  var rowNotes = [];
  for (var i = 0, l = values.length; i < l; i++)
  {
    rowNotes = notes[i];
    values[i].forEach(getResult_);
  }
  return data;
}


text:
Q: TNotebook or TPageControl I have an application using TNotebook to switch between different sub pages, that are shown.
Now I have to extend this code a little bit (namely add a page and change sizes).
I was told that TNotebook shouldn't be used anymore. In Delphi's help  I find "New applications should use TPageControl".
My question: Should I refactor the code to use TPageControl instead of TNotebook? What are the disadvandtages of TNotebook?

A: The main advantage of TPageControl, in my opinion, is that it is a system native control, unlike TNotebook. When you use system native controls, the control is painted by the system, and so takes on the look and appearance that is native to the operating system that you use.
When the application is run on a new version of the OS, your control automatically gets the appearance that is native to that OS. What's more, the behaviour is system native. By that I mean the way the control responds to keyboard input and so on. That's less of an issue with TPageControl since the system does not provide that much default behaviour. But as a general rule the advice is sound.
When none of the system native controls meet your specific requirements, you may need to use a non-native control. And then you have to work to make sure that your control adapts to its surroundings. But when there is a system native control, unless there is a strong reason to avoid it, you should use it.

A: Another disadvantage of TNotebook is that it excludes the form or frame on which it is placed from inheritance.


text:
Q: Spring RequestParam with angular number format Cors error So i am trying to make a post request to this endpoint with 2 paramerers as numbers...i get the parameters  corectly.. when is posted i get
Access to XMLHttpRequest at 'http://localhost:8080/api/user/addCartItem' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. error ...
When i apply the same method from postman everythink works smooth and corectly.
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
    @RequestMapping(value = "/addCartItem/{cartId}{productId}", method = RequestMethod.POST )
    public List<CartItem> addCartItem(@RequestParam Long cartId ,
                                      @RequestParam Long productId) {
        return cartService.addCartItem(cartId ,productId);
    }

  addCartItem(cartId:number,productId:number):Observable<any>{
    const httpParams = new HttpParams({
      fromObject:{
        cartId,
       productId,
      }
    })
    return this.httpClient.post('http://localhost:8080/api/user/addCartItem',{ httpParams })
  }

This is the Security Config Class
@EnableWebMvc
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
  prePostEnabled = true)
public class SecutiryConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsServiceImpl userDetailsService;
    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;
    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }
    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests().antMatchers("/api/auth/**").permitAll()
            .antMatchers("/api/admin/**").permitAll()
            .antMatchers("/api/user/**").permitAll()
            .antMatchers("/api/public/**").permitAll()
            .anyRequest().authenticated();
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                 registry.addMapping("/**")
                 .allowedMethods("GET","POST","PUT","DELETE")
                 .allowedHeaders("*")
                 .allowedOrigins("*");
            }
        };
    }
}


text:
Q: Use MediaScannerConnection scanFile To Scan Downloaded Image File I am working on an app in which I save image(s) to a directory but the Images wont show up in gallery until I restart the phone.
Here's My Code Snippet
public class SaveTask extends AsyncTask<String , String , String>
        {
            private Context context;
            private ProgressDialog pDialog;
            String image_url;
            URL myFileUrl;
            String myFileUrl1;
            Bitmap bmImg = null;
            File file ;

            public SaveTask(Context context) {
                this.context = context;
            }

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub

                super.onPreExecute();

                pDialog = new ProgressDialog(context);
                pDialog.setMessage("Downloading Image ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();

            }

            @Override
            protected String doInBackground(String... args) {
                // TODO Auto-generated method stub

                try {

                    myFileUrl = new URL(args[0]);
                    //myFileUrl1 = args[0];

                    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bmImg = BitmapFactory.decodeStream(is);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                try {

                    String path = myFileUrl.getPath();
                    String idStr = path.substring(path.lastIndexOf('/') + 1);
                    File filepath = Environment.getExternalStorageDirectory();
                    File dir = new File (filepath.getAbsolutePath() + "/mydownloaddir/");
                    dir.mkdirs();
                    String fileName = idStr;
                    file = new File(dir, fileName);
                    FileOutputStream fos = new FileOutputStream(file);
                    bmImg.compress(CompressFormat.JPEG, 75, fos);
                    fos.flush();
                    fos.close();

                }
                catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                return null;
            }

            @Override
            protected void onPostExecute(String args) {
                // TODO Auto-generated method stub
                Toast.makeText(SlideImageActivity.this, "Image Saved Succesfully to Folder 'mydownloaddir'", Toast.LENGTH_SHORT).show();
                pDialog.dismiss();
            }
        }

What code should I use next to make the Images showup in gallery using medisscanner
I got something like this on here But unable to use it properly:
MediaScannerConnection.scanFile(ApplicationContext.context, new String[] { imageFile.getPath() }, null,
          new MediaScannerConnection.OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String path, Uri uri) {
              Log.i(TAG, "Scanned " + path);
            }
          });

Please Help

A: Use
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
            + Environment.getExternalStorageDirectory())));

//but it only works on API <19
Second Method
private void scanFile(String path) {

        MediaScannerConnection.scanFile(MainActivity.this,
                new String[] { path }, null,
                new MediaScannerConnection.OnScanCompletedListener() {

                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("TAG", "Finished scanning " + path);
                    }
                });
    }

Call it like
scanFile(yourFile.getAbsolutePath());

Also see this Answer


text:
Q: Can I not use multiple Exceptions? When I try to use multiple exceptions, for some reason I get the error:
SyntaxError: default 'except:' must be last

Code:
try:
    to_address = item["tx"]
    amount_xrp = int(item["tx"]["TakerGets"])/1000000.0
except:
    to_address = item["tx"]
except:
    to_address = "Cancellation"#item["tx"]["TakerPays"]
    amount_xrp = "NA"

A: The except: clause catches any exception.  There's no sense in using it twice.  What would it mean?

A: Your example is not correct Python syntax. You could do the following:
try:
    to_address = item["tx"]
    amount_xrp = int(item["tx"]["TakerGets"])/1000000.0

except:
    try:
        to_address = item["tx"]

    except:
        to_address = "Cancellation"#item["tx"]["TakerPays"]
        amount_xrp = "NA"

A: My best guess at what you're trying to achieve  here is to have to_address be set to Cancellation if it's not in items, and have amount_xrp be set to 'NA' if to_address doesn't have a 'TakerGets' key.
to_address = item.get('tx', 'Cancellation') #returns 'Cancellation' if no key 'tx'
amount_xrp = 'NA'

if to_address != 'Cancellation':
    try:
        amount_xrp = int(to_address["TakerGets"])/1000000.0
    except KeyError:
        pass


text:
Q: Create Custom Content Type in SPFx I have crated an SPFx app using this link https://dev.office.com/sharepoint/docs/spfx/web-parts/get-started/provision-sp-assets-from-package
i have created a list, a content type and a few columns in it.
as an upgrade to the app i create another list. all of these things works fine.
Now i want to create a new content type, add a few more site columns , attach the site columns to the Content type (existing and new).

A: You can do it the same way you did it previously for your contenttype in the same elements.xml file.
You can have multiple Fiels, ContentTypes and ListInstances in one elements.xml file.


text:
Q: Splash screen exhibiting abrupt motion before switching to the main screen A splash screen implemented to be displayed while the Xamarin app loads in the background exhibits an unanticipated "upwards movement" while being displayed before switching to the main screen in Android devices (as seen in the following GIF of the loading screen).

My first assumption regarding the solution of this issue was to use the same style settings for both the splash screen activity and the main activity but it is to no avail as the unwanted motion is still exhibited, which, as of this moment, is completely baffling as the cause just cannot be segregated.
The splash screen is implemented as per the logic corresponding to the following code and style sheets in the Android Project:
Resources/drawable/splash_screen.xml
<?xml version="1.0" encoding="utf-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <color android:color="@color/splash_screen_background"/>
  </item>
  <!-- For bitmap images -->
  <!--<item>
    <bitmap
        android:src="@drawable/app_icon"
        android:tileMode="disabled"
        android:gravity="center"/>
  </item>-->
  <!-- For Android's drawable vector images -->
  <item
    android:drawable="@drawable/android_v_drawable_application_icon"
    android:gravity ="center"
    android:width="150dp"
    android:height="214.010dp" />
</layer-list>

values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="launcher_background">#FFFFFF</color>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="splash_screen_background">#FFFFFF</color>
</resources>

value/styles.xml
<?xml version="1.0" encoding="utf-8" ?>
<resources>

  <style name="MainTheme" parent="MainTheme.Base">
  </style>
  <!-- Base theme applied no matter what API -->
  <style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <!--If you are using revision 22.1 please use just windowNoTitle. Without android:-->
    <item name="windowNoTitle">true</item>
    <!--We will be using the toolbar so no need to show ActionBar-->
    <item name="windowActionBar">false</item>
    <!-- Set theme colors from https://aka.ms/material-colors -->
    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">#2196F3</item>
    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">#1976D2</item>
    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <item name="colorAccent">#FF4081</item>
    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight and colorSwitchThumbNormal. -->
    <item name="windowActionModeOverlay">true</item>

    <item name="android:datePickerDialogTheme">@style/AppCompatDialogStyle</item>
  </style>

  <style name="AppCompatDialogStyle" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">#FF4081</item>
  </style>

  <style name="SplashScreenTheme" parent ="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowBackground">@drawable/splash_screen</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowActionBar">false</item>
    <item name="windowActionModeOverlay">true</item>
  </style>
</resources>

Attributes to the Android Activity class pertaining to the splash screen:
[Activity(Label = "App_App1",
        Theme = "@style/SplashScreenTheme",
        Icon = "@mipmap/icon",
        ConfigurationChanges = ConfigChanges.ScreenSize
                                | ConfigChanges.Orientation,
        MainLauncher = true,
        NoHistory = true,
        ScreenOrientation = ScreenOrientation.Portrait
        )]

Thanks in advance.

A: I make the code sample to reproduce the "upwards movement".
In your description, you said "switching to the main screen in Android devices". I guess you have a special activity to do the splash screen. And have the main activity to LoadApplication.
When i set the same splash screen theme for the Splash_Activity and MainActivity, it would occure the "upwards movement".

So set the Theme to null or the default, it would be okay.

Splash_Activity:
 [Activity(Label = "App_App1",
    Theme = "@style/SplashScreenTheme",
    Icon = "@mipmap/icon",
    ConfigurationChanges = ConfigChanges.ScreenSize
                            | ConfigChanges.Orientation,
    MainLauncher = true,
    NoHistory = true,
    ScreenOrientation = ScreenOrientation.Portrait
    )]

MainActivity:
 [Activity(Label = "SplashScreen", Icon = "@mipmap/icon", Theme = "@style/MainTheme", NoHistory = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]

You could download the source file from the GitHub for reference.
https://github.com/WendyZang/Test/tree/master/SplashScreen2/SplashScreen

A: Removing the parent attribute of the <style> tag adhering to the splash screen (i.e. the <style> tag with the attribute name="SplashScreenTheme", in this case) removes the unwanted behavior.


text:
Q: What should I use to Partition a Windows 2003 server? I'm trying to partition a Windows 2003 server, and I was wondering what my options are to partition the drive. Currently the 1.9 TB is dedicated to the C:/. We're using an IBM server with a 8 drive array, I can't remember the specific model though. I tried to use partition Magic but I just found out it doesn't do windows 2003 systems. Looking into it I found one of my options is Acronis Partition Expert, but is there any other way I could partition the server (preferably without spending $50)?

A: You could try booting off a Parted Magic CD then use GParted. Backup first :-)

A: Just confirming what AdamB has wrote, GParted is amazing. Used it earlier today without hassle.
If you have Ubuntu Live CD it's on there as well.


text:
Q: how to change x-axis limits ggplot2 r I would like to set limit for x-axis using ggplot bar plot. The whole plot is ok, but when I use ylim(1,6) (these are limits what I need) the bars disappear.
Data:
var.A <- as.numeric(c(1:13))
var.B <- c(4.351833, 2.938000, 4.726465, 3.747162, 3.720737, 4.297117, 4.304500, 4.061277, 4.595236, 4.105444, 3.701684, 3.523563, 4.170000)
df <- data.frame(var.A,var.B)

Ggplot code:
    ggplot(df, aes(x=factor(var.A), y=var.B)) +
  geom_bar(position=position_dodge(), stat="identity", fill="#fff68f", colour="darkgrey", width = 0.4) +
  coord_flip()+
  xlab("") +
  ylab("") +
  scale_x_discrete(labels=c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd",
                            "eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii",
                            "jjjjjj","kkkkkkk","llllll","mmmmmmmm"))

And when I add: ylim(1,6) + things are going wrong.
And another thing. The color of every bar is set as fill="#fff68f". Is there any solution to change color of one bar, for example the first from top I'd like to be different, i.e. #ee2c2c.

A: Because you used coord_flip() you can set limits of x-axis with scale_y_continuous(expand=c(0,0),limits=c(1,6),oob = rescale_none) and for setting colors for every bar you can use scale_fill_manual(values = c("#ee2c2c",...).
So if you would like to set the color of bars manually, you first need to create vector of names and insert it in your dataframe:
names <- c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd",
"eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii",
"jjjjjj","kkkkkkk","llllll","mmmmmmmm")

var.A <- as.numeric(c(1:13))
var.B <- c(4.351833, 2.938000, 4.726465, 3.747162, 3.720737, 4.297117, 4.304500, 4.061277, 4.595236, 4.105444, 3.701684, 3.523563, 4.170000)
df <- data.frame(var.A,var.B,names)

And to order variable names and colors in ggplot you need to change the structure of vector from character to factor (in order to get levels).

var.names = factor(df$names,
                levels = c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd", "eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii", "jjjjjj","kkkkkkk","llllll","mmmmmmmm"), ordered=T)

So your code then looks like:
ggplot(df, aes(x=var.names, y=var.B, fill=as.factor(var.names))) +
  geom_bar(position=position_dodge(), stat="identity", width = 0.4) +
  coord_flip()+
  scale_y_continuous(expand=c(0,0),limits=c(1,6),oob = rescale_none) +
  xlab("") +
  ylab("") +
  scale_fill_manual(values = c(c(rep("#fff68f",12)),"#ee2c2c"))

And output is


text:
Q: How to get my program to read third if statement I am trying to get my program to move a "sushi plate" clockwise in a rectangular fashion although it won't seem to continue moving after my third if statement:
from graphics import *
win =GraphWin("Draw and Animate",640,480)
win.setBackground("wheat1")

#Right
xmove = 1
ymove = 0
#Down
xmove2 = 0
ymove2 = 1
#Left
xmove3 = -1
ymove3 = 0
#Up
xmove4 = 0
ymove4 = -1

sushiplate = Rectangle(Point(300,160),Point(340,180))
sushiplate.setFill("white")
sushiplate.draw(win)

leftsushi = Circle(Point(310,170), 5)
leftsushi.setOutline("Green")
leftsushi.setFill("orange")
leftsushi.draw(win)

rightsushi = Circle(Point(330,170), 5)
rightsushi.setOutline("Green")
rightsushi.setFill("orange")
rightsushi.draw(win)

while(True):
    #Move sushi

    sushiplate.move(xmove4, ymove4)
    leftsushi.move(xmove4, ymove4)
    rightsushi.move(xmove4, ymove4)
    sushicenter = sushiplate.getCenter()
    if (sushicenter.getY()<=130):
        xmove4 = xmove
        ymove4 = ymove
    if (sushicenter.getX()>=510):
        xmove = xmove2
        ymove = ymove2
    if (sushicenter.getY()>=360):
        xmove2 = xmove3
        ymove2 = ymove3

    update(60)

My sushi plate will move up, right, down but will continue moving down and my third if statement will not run:
if (sushicenter.getY()>=360):
    xmove2 = xmove3
    ymove2 = ymove3

A: These conditions should be at the same level and not nested. Since the second level if checks sushicenter.getY() <= 130, then your fourth level condition can only be triggered if getY() is both >=360 and <=130 and that can never happen.
I think you meant to keep them at the same level so they can be independently triggered and not depend on the other conditions.
from graphics import *
win =GraphWin("Draw and Animate",640,480)
win.setBackground("wheat1")

#Right
xmove = 1
ymove = 0
#Down
xmove2 = 0
ymove2 = 1
#Left
xmove3 = -1
ymove3 = 0
#Up
xmove4 = 0
ymove4 = -1

sushiplate = Rectangle(Point(300,160),Point(340,180))
sushiplate.setFill("white")
sushiplate.draw(win)

leftsushi = Circle(Point(310,170), 5)
leftsushi.setOutline("Green")
leftsushi.setFill("orange")
leftsushi.draw(win)

rightsushi = Circle(Point(330,170), 5)
rightsushi.setOutline("Green")
rightsushi.setFill("orange")
rightsushi.draw(win)

while(True):
    #Move sushi

    sushiplate.move(xmove4, ymove4)
    leftsushi.move(xmove4, ymove4)
    rightsushi.move(xmove4, ymove4)
    sushicenter = sushiplate.getCenter()
    if (sushicenter.getY()<=130):
        xmove4 = xmove
        ymove4 = ymove
    if (sushicenter.getX()>=490):
        xmove = xmove2
        ymove = ymove2
    if (sushicenter.getY()>=360):
        xmove2 = xmove3
        ymove2 = ymove3
    if(sushicenter.getX()<=120):
        xmove3 = xmove4
        ymove3 = ymove4

    update(60)

A: You're already under the if (sushicenter.getY()<=130): branch.  sushicenter.getY()>=360 can't possibly be true in that case.

A: The problem is that once a condition like this triggers:
 if (sushicenter.getX()>=510):

It continues to trigger every time as the result is a change to the Y direction and the object is fixed in the X direction.  Cases after this one never trigger.  We can fix this by first "testing the waters" to see if the move might trigger a change and then make the movements afterward.  My rewrite of your code below does this but also tries to get rid of numbers in favor of symbols as all the numbered variables were confusing, even to you given the bugs in the code:
from graphics import *

WIDTH, HEIGHT = 640, 480
BORDER = 130
RADIUS = 5
DIAMETER = RADIUS * 2

# Right
XMOVE_RIGHT = 1
YMOVE_RIGHT = 0
# Down
XMOVE_DOWN = 0
YMOVE_DOWN = 1
# Left
XMOVE_LEFT = -1
YMOVE_LEFT = 0
# Up
XMOVE_UP = 0
YMOVE_UP = -1

win = GraphWin("Draw and Animate", WIDTH, HEIGHT)
win.setBackground('wheat1')

sushiplate = Rectangle(Point(BORDER - DIAMETER * 2, BORDER - DIAMETER), Point(BORDER + DIAMETER * 2, BORDER + DIAMETER))
sushiplate.setFill('white')
sushiplate.draw(win)

leftsushi = Circle(Point(BORDER - DIAMETER, BORDER), RADIUS)
leftsushi.setOutline('green')
leftsushi.setFill('orange')
leftsushi.draw(win)

rightsushi = Circle(Point(BORDER + DIAMETER, BORDER), RADIUS)
rightsushi.setOutline('green')
rightsushi.setFill('orange')
rightsushi.draw(win)

xmove = XMOVE_RIGHT
ymove = YMOVE_RIGHT

while True:
    # Move sushi

    center = sushiplate.getCenter()
    x, y = center.getX() + xmove, center.getY() + ymove

    if x > WIDTH - BORDER:
        xmove, ymove = XMOVE_DOWN, YMOVE_DOWN
    elif y > HEIGHT - BORDER:
        xmove, ymove = XMOVE_LEFT, YMOVE_LEFT
    elif x < BORDER:
        xmove, ymove = XMOVE_UP, YMOVE_UP
    elif y < BORDER:
        xmove, ymove = XMOVE_RIGHT, YMOVE_RIGHT

    for meal_object in (sushiplate, leftsushi, rightsushi):
        meal_object.move(xmove, ymove)

    update(60)


text:
Q: React Router Link Not Rendering Component So I'm using this <Link> component from react, now the issue is if I write
<Link to='/pathname'> Text </Link>
it works perfectly... but if I write
<Link to={{ pathname:pathname, state: {data:data} }}>Text</Link>
then it changes the url, but doesn't mount the intended component, neither it keeps the previous one, so I'm left with an empty white page.
Though if I refresh, then it loads all the data I intended to load. Why isn't the desired Component rendering ??


text:
Q: Wrong url with Django Sorl thumbnail with Amazon s3 I am having a very strange error in using sorl thumbnails in my django project which uses S3 for media files. I have done my settings as pointed out in this answer https://stackoverflow.com/a/12848650/538191 and in fact all my other media files are being generated correctly.
But for the images generated through sorl thumbnails I am getting a url like this
https://he-s3.s3.amazonaws.com/cache/6f/cb/6fcb83175cb63f754fba9facec5dda7f.jpg?Signature=tgDEXyRV3gl3QtK%2BvwliqAtWqpM%3D&Expires=1357853609&AWSAccessKeyId=AKIAJLE6MUHDYS3HN6YQ
The problem is strange because its appending the S3 storage path to the image url, but its not adding /media/ in between. If you check
https://he-s3.s3.amazonaws.com/media/cache/6f/cb/6fcb83175cb63f754fba9facec5dda7f.jpg
the image actually exists there, but since the url is being generated wrong, I am getting a broken image. In the settings file I have declared the DEFAULT_FILE_STORAGE using s3boto and it contains
S3_URL = 'http://he-s3.s3-website-ap-southeast-1.amazonaws.com'
MEDIA_URL = S3_URL + '/media/'

I fail to understand why does the path in the sorl thumbnail image not contain media.
Any help is appreciated.
Update
Instead of being solved, the problem has in fact compounded. What I did was that I cleared the KVStore in thumbnail and all the database was cleared. I was happy because I thought the problem was solved, I was getting the correct url now. But then I refreshed the page, and again I was getting the wrong url. I don't understand what's happening, if I clear the thumbnail db, it shows the correct url once and after that it again shows the wrong url.

A: I'll bet that you're using something like this:
MediaS3BotoStorage = lambda: S3BotoStorage(location='media')

However this causes problems in sorl-thumbnail because it serializes the storage class into cache using the class name.  Later when it deserializes, it instantiates as S3BotoStorage() without the location parameter.  That's why it works the first time for you but then fails later.
You can fix it by using a full-fledged class instead of a factory:
class MediaS3BotoStorage(S3BotoStorage):
    location = 'media'

Hope that helps!


text:
Q: Uncaught SyntaxError: missing ) after argument list (while calling a js function) I am trying to pass multiple values as a parameter on click event as below:
<c:forEach var="ct" items="${contactmsglist}">

</c:forEach>

How can I resolve that error:

Uncaught SyntaxError: missing )

after argument list.

A: Try adding quote arround your arguments if they are string :
<c:forEach var="ct" items="${contactmsglist}">

</c:forEach>

A: Single quote missing, I think thats the issue here
    <c:forEach var="ct" items="${contactmsglist}">

   </c:forEach>


text:
Q: TCP Server Timeout while peeking stream reader error I have a TCP server which has a receive timeout of 9 seconds, however, I am using to receive any data from the client:
while (sr.Peek() >= 0) {
    line += sr.ReadLine();
    line += Environment.NewLine;
}

But when the server times out I get the following error on the sr.Peek() line:

System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Is there a way of having a timeout but also waiting for any potential data from the client?


text:
Q: C Programming segfault when iterating through directories I am needing to walk a directory and perform a sort of grep on each file I come across.
Here is some code, I have the function kicked off in a thread because I want to main to continue with it's tasks. For some reason
it finishes the iteration and then segfaults.
Why is this segfaulting? What am I doing wrong? How should I fix this?
int main(int argc, char **argv){
 int ccn = 1;

  if(ccn == 1){
  pthread_t thread_id;
      char *path = ".";
    pthread_create( &thread_id, NULL, list_dir("."), (void*) path);
}
   /*code continues
    ...
    ...
   */
 }

>
void *list_dir (const char * dir_name)
{
    DIR * d;

    /* Open the directory specified by "dir_name". */

    d = opendir (dir_name);

    /* Check it was opened. */
    if (! d) {
        fprintf (stderr, "Cannot open directory '%s': %s\n",
                 dir_name, strerror (errno));
        exit (EXIT_FAILURE);
    }
    while (1) {
        struct dirent * entry;
        const char * d_name;

        /* "Readdir" gets subsequent entries from "d". */
        entry = readdir (d);
        if (! entry) {
            /* There are no more entries in this directory, so break
               out of the while loop. */
            break;
        }
        d_name = entry->d_name;
        /* Print the name of the file and directory. */
    printf ("%s/%s\n", dir_name, d_name);

#if 0
    /* If you don't want to print the directories, use the
       following line: */

        if (! (entry->d_type & DT_DIR)) {
        printf ("%s/%s\n", dir_name, d_name);
    }

#endif /* 0 */

        if (entry->d_type & DT_DIR) {

            /* Check that the directory is not "d" or d's parent. */

            if (strcmp (d_name, "..") != 0 &&
                strcmp (d_name, ".") != 0) {
                int path_length;
                char path[PATH_MAX];

                path_length = snprintf (path, PATH_MAX,
                                        "%s/%s", dir_name, d_name);
                printf ("%s\n", path);
                if (path_length >= PATH_MAX) {
                    fprintf (stderr, "Path length has got too long.\n");
                    exit (EXIT_FAILURE);
                }
                /* Recursively call "list_dir" with the new path. */
                list_dir (path);
            }
    }
    }
    /* After going through all the entries, close the directory. */
    if (closedir (d)) {
        fprintf (stderr, "Could not close '%s': %s\n",
                 dir_name, strerror (errno));
        exit (EXIT_FAILURE);
    }
    return 0; // This is demanded for a void * ...
}

A: Your problem is this line:
pthread_create( &thread_id, NULL, list_dir("."), (void*) path);

pthread_create() expects a pointer to the function the new thread should execute. But writing list_dir(".") calls the function (before even calling pthread_create()). Whatever it returns is fed to pthread_create() as the address of the function to execute in the thread.
In your case, you do return 0 at the end of your function, so pthread_create() will try to dereference the nullpointer when finally starting the thread, that's the reason for your crash.
To correctly pass the function pointer, you can use the address-of operator (&list_dir), or just the identifier of the function, which evaluates as a pointer to the function as well:
pthread_create( &thread_id, NULL, list_dir, path);

I also removed the unnecessary void * cast here: Any data pointer can be implicitly converted from and to void * in C.
But there's another problem, your function signature currently reads:
void *list_dir (const char * dir_name)

pthread_create() expects a function that takes a void * argument. On most platforms, it would actually work the way you wrote it, but it's still wrong and can go wrong in practice, because there's no guarantee in C that a char * pointer has the same internal representation as a void * pointer. So, you have to actually do the conversion. Change your function to take void * and convert the pointer to the correct type in the first line, e.g. like this:
void *list_dir(void *arg) {
    const char *dir_name = arg;


text:
Q: Calculating skewness of a data distribution in SQL in Access without an additional subquery I have a dataset in an Access database that, for simplicity's sake, looks like this:

      ID     Group   Employee       Ticket ID
    ------ --------- -------- -----------------
      1        A       Joe           123414
      2        A       Joe           12309124
      3        A       Bob           112321321
      4        A       Bob           213123214142
      5        A       Sam           123214214124
      6        B       Jen           412949218419
      7        B       Amy           12341234213

What I'm trying to do is calculate the statistical skewness of distribution of the number of tickets each employee has handled.
In a perfect world, my SQL would be this:
SELECT
    [Group], SKEW([myCount]) AS mySkew
FROM
    (
     SELECT [Group], [Employee], COUNT(*) AS myCount
     FROM MyTable
     GROUP BY [Group], [Employee]
    )
        AS TempTable
GROUP BY
   [Group];

However, it appears that Access does not have a SKEW function.  Anyone know how I can do this calculation?

A: It looks like somebody has tried this and created a small library for it here:
http://www.experts-exchange.com/Microsoft/Development/MS_Access/A_2529-Median-Mode-Skewness-and-Kurtosis-in-MS-Access.html


text:
Q: What constitutes Ruby coverage measurement with simplecov gem While running simplecov on Mac OSX, the resulting coverage makes little sense.
If the following test is run:
rails test test/models/channel_test.rb
> 4 runs, 4 assertions, 0 failures, 0 errors, 0 skips
> Coverage report generated for Minitest to /Volumes/[...]/coverage. 0 / 0 LOC (100.0%) covered.

Yet when running rails test test/models the graphical output indicates for test/models/channel_test.rb
require "test_helper"
class ChannelTest < ActiveSupport::TestCase
  test "invalid if name not defined" do
    channel = Channel.new(priority: 1, unit_cost: 1, daily_limit: 9999)
    assert_not channel.valid?
    assert_not channel.save, "Saved the channel without a name"
  end

update  I presumed it might have been the chosen syntax of the test that might be a flaw - I added a supplemental test and the result is still reported
for the model  3 relevant lines. 0 lines covered and 3 lines missed.
class Channel < ApplicationRecord # red

  validates :name, presence: true # red

end # red

Thus the test is passing, but the coverage result is confounding:
a) as a standalone, the coverage count is 0/0, whereas the tests pass
b) what constitutes a miss or conversely coverage by a (the?) test ?
test_helper.rb
 require 'simplecov'
 SimpleCov.start

ENV['RAILS_ENV'] ||= 'test'
require_relative "../config/environment"
require "rails/test_help"
require 'webmock/minitest'

class ActiveSupport::TestCase
  parallelize(workers: :number_of_processors)

  fixtures :all

  def log_in_as(user, shop)
    post user_session_url, params: { user_id: user.id, active_shop_id: @site.shop_id }
  end

end

Update 2  As per @BroiSatse suggestion, commenting out parallelize(workers: :number_of_processors)
allows coverage to be measured.


text:
Q: Is the torchvision MNIST loader not working properly or am I doing something wrong? I wanted to see that the images I used in my network were OK, so I saved a bunch of them using the following code:
train_set = dset.MNIST(root=root, train=True, transform=transforms.ToTensor(), download=download)

for it, (img, target) in enumerate(train_loader):
    X = Variable(img)
    tar = Variable(target)
    X = X.view(batch_size, -1)
    cur_img_batch = X.data.numpy()
    cur_tar_batch = tar.data.numpy()
    for i in range(batch_size):
        cur_img = cur_img_batch[i]
        im = Image.fromarray(cur_img.reshape((28, 28)).astype('uint8') * 255)
        if cur_tar_batch[i] == 8:
            im.save(test_img_dir + 'iter_' + str(it) + '_sample_' + str(i) + '.png')

This isn't the cleanest code, but it just saves a bunch of images that are all labeled as '8'. Upon opening them, I see that most of them look like  this, even though a small minority of them are perfectly fine.
Am I doing something wrong?

A: From the comments:
The issue was in this line cur_img.reshape((28, 28)).astype('uint8') * 255, converting the normalized image to integer before multiplying it by 255, thus resulting in images with either 0 or 255.
The updated code:
train_set = dset.MNIST(root=root, train=True, transform=transforms.ToTensor(), download=download)

for it, (img, target) in enumerate(train_loader):
    X = Variable(img)
    tar = Variable(target)
    X = X.view(batch_size, -1)
    cur_img_batch = X.data.numpy()
    cur_tar_batch = tar.data.numpy()
    for i in range(batch_size):
        cur_img = cur_img_batch[i]
        im = Image.fromarray((cur_img.reshape((28, 28)) * 255).astype('uint8'))
        if cur_tar_batch[i] == 8:
            im.save(test_img_dir + 'iter_' + str(it) + '_sample_' + str(i) + '.png')


text:
Q: Text in Ellipses JavaFX I created a custom venn chart for two sets an their intersection in JavaFX.
Now I want to show the number of elements in this sets like in the following picture:

The sets are ellipses and I used masks to give the intersection a different color.
Now I want to show the number with size and position related to the available space so that the numbers are always inside the according area.
The width for the text element is easy to calculate, but I don't know how to get available height for the text elements.
Maybe it could be helpful to have the pixels of the ellipses as path, but I have no idea to how I can get this.
Does anyone know how to implement that?
Edit:
I developed an algorithm to find the size of a rectangle, which fits in the required areas of the ellipses. The text are scaled to the size of the rectangle and it works, but now I have another problem.
I need to center the scaled text in the rectangle an I used a StackPane for that. But I can't position the StackPane in the chart parent. If I set the layoutX and layoutY the bounds in parent are different.
For example: stackPane with text = sp;
sp.setLayoutY(122.1662320906945);
The Result for getBoundsInParent().getMinY() is 97.16622924804688;
How can I set the StackPane position, if I use it in a chart class as chart children?


text:
Q: How to schedule task using Quartz.net 2.0? I am trying to schedule a task using Quartz.net 2.0 in ASP.NET MVC 4 application, but i can not get the task to be executed.
Here is the code:
public class ScheduleTaskConfig
{
    public static void StartScheduler()
    {
        ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

        IScheduler scheduler = schedulerFactory.GetScheduler();

        JobKey emailSenderTaskKey = new JobKey("emailSenderTask", "email");
        IJobDetail emailSenderTask = JobBuilder.Create<QueuedEmailsSendTask>()
            .WithIdentity(emailSenderTaskKey)
            .Build();

        TriggerKey emailSenderTriggerKey = new TriggerKey("emailSenderTrigger", "email");
        ITrigger emailSenderTrigger = TriggerBuilder.Create()
            .WithIdentity(emailSenderTriggerKey)
            .WithSimpleSchedule(s => s.RepeatForever().WithIntervalInSeconds(5))
            .StartNow()
            .Build();

        scheduler.ScheduleJob(emailSenderTask, emailSenderTrigger);
        scheduler.Start();
    }
}

It is called in global.asax application start
protected void Application_Start()
{
    ScheduleTaskConfig.StartScheduler();
    ...
}

And here is the class that implements the IJob interface:
public class QueuedEmailsSendTask : IJob
{
    private IQueuedEmailsService _queuedEmailsService { get; set; }
    private IEmailSenderService _emailSenderService { get; set; }

    public QueuedEmailsSendTask(IQueuedEmailsService queuedEmailsService, IEmailSenderService emailSenderService)
    {
        this._queuedEmailsService = queuedEmailsService;
        this._emailSenderService = emailSenderService;
    }

    public void Execute(IJobExecutionContext executeContext)
    {
        //do stuff ...
    }
}

I placed a breakpoint at the beginning of the Execute method, but the debugger does not stop there. What am i doing wrong?
UPDATE:
It has something to do with the class that implements the IJob interface not having a default constructor.
It works, if I modify the constructor like this:
public QueuedEmailsSendTask()
{
}

But I need to be able to inject my dependencies. I am using the Autofac IoC container.

A: To make Quartz.net work with an IoC container you need to have a factory class implementing IJobFactory:
public class AutofacJobFactory : IJobFactory
{
    private readonly IContainer _container;

    public AutofacJobFactory(IContainer container)
    {
        _container = container;
    }

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        return (IJob)_container.Resolve(bundle.JobDetail.JobType);
    }
}

The JobFactory instance then needs to be assigned to the scheduler in the initialization code:
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
IScheduler scheduler = schedulerFactory.GetScheduler();
scheduler.JobFactory = new AutofacJobFactory(container);

And don't forget to register the job in the IoC container.

A: Have you tried scheduling the job after starting the scheduler?
public class ScheduleTaskConfig
{
    public static void StartScheduler()
    {
        ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

        IScheduler scheduler = schedulerFactory.GetScheduler();
        scheduler.Start(); //start here

        //construct job info

        scheduler.ScheduleJob(emailSenderTask, emailSenderTrigger); //schedule here
    }
}

A: You need to ensure that the AutofacJobFactory is responsible for instantiating the job. This means not using the JobBuilder object. Instead you should pass the details of the job to be created by the scheduler's AutofacJobFactory in the form of a JobDetailImpl  object. Your working code would look something like the following.
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

IScheduler scheduler = schedulerFactory.GetScheduler();
scheduler.JobFactory = new AutofacJobFactory(container);
scheduler.Start(); //start here

// construct job info
JobDetailImpl jobDetail = new JobDetailImpl("emailSenderTask", null, typeof(QueuedEmailsSendTask));

TriggerKey emailSenderTriggerKey = new TriggerKey("emailSenderTrigger", "email");
ITrigger emailSenderTrigger = TriggerBuilder.Create()
    .WithIdentity(emailSenderTriggerKey)
    .WithSimpleSchedule(s => s.RepeatForever().WithIntervalInSeconds(5))
    .StartNow()
    .Build();

sched.ScheduleJob(jobDetail, trigger);

For a complete example, please see the following question How do I create a Quartz.NET's job requiring injection with autofac


text:
Q: IE extra space above inline-block/text-top (transitional doctype) I get an extra space above the below textarea, but only in ie. How to fix it?

    Info<textarea cols="40" rows="4"></textarea>

.field {
     margin: 0px;
     margin-top: 2px;
}

label {
     display: inline-block;
     width: 5em;
     margin-right: 0.5em;
}

textarea {
     display: inline-block;
     width: 22em;
     vertical-align: text-top;
}

If I put a whitespace between label and textarea tags the space disappears. But then I get a horizontal extra space between them.
Edit:
I found, the problem appears with doctype - transitional. With strict everithing is ok. Is there a way, to fix it with transtional?

A: I can reproduce your issue. See the end of my answer for exact details.
You can remove the gap by:

*

*Changing vertical-align: text-top to vertical-align: top.

Unless you desperately need text-top for some reason (why?), this is an easy remedy.
I'm not sure why text-top adds the extra space at the top with the Transitional doctype.

Testing in IE8, with this code (XHTML 1.0 Transitional), your described issue happens:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

    Info<textarea cols="40" rows="4"></textarea>

If I change the first line to this (XHTML 1.0 Strict), it doesn't happen:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


text:
Q: YA novel about archaeologist exploring space Read it in the '90s. YA novel starting in overpopulated, urban Earth. Young guy manages to get a berth or sneak onto a space ship set to explore potential planets for colonization, despite poor qualifications. He is educated in archaeology. There are scenes in the ship where he is interacting with onboard tech and working in a hydroponic garden with some Asian botanist/gardener.
He ends up helping explore some alien planet that was thought to be uninhabited, but he finds an alien cave and takes his video recording device that stores video on a 3D optical crystal, records and decodes alien runes, and determines there is something toxic? on the planet, perhaps toxic to aliens but ok for humans to settle down?

A: I don't know how close it is, but this reminds me of Robert Silverberg's young adult novel Across a Billion Years (1969).
The hero, Tom Rice, is a graduate student of archeology, joining his first field expedition to investigate some precursor remains.  He uses recording cubes to send "letters" to his sister back on Earth.
Of course, since he's the protagonist, he makes an important discovery of actual recordings of the precursors which lead the expedition on a hunt.
I don't recall anything about translating a message about a toxin, though.


text:
Q: Postgresql copy CSV format, double quote escape not working Running into an issue with copying the following data into a DB
1, ab\"c
I receive an unterminated quote error when running the following SQL
copy table_name from sample.tsv CSV DELIMITER ',' QUOTE '"' ESCAPE E'\\'
Based on the postgresql documentation I expect the escape parameter to be used to escape the quotation character but it's not working. Would like to see if there's a solution to this issue without reformatting the data, or changing the quote character.

A: try this. Because if quote is ", then it will mix with double quote in (ab"c).
copy table_name from 'sample.tsv' (FORMAT CSV, QUOTE '''', DELIMITER ',',ESCAPE E'\\');

A: It is expecting to find escaped quotes only inside quotes, so the command you show would work for 1,"ab\"c" but not for what you have.
The command that would work for the data you show is:
copy table_name from sample.tsv DELIMITER ','

But it is not likely to work for the rest of your data.


text:
Q: ServiceForbidden Exception while adding entry to google calendar I am trying to add an entry in google calendar but getting service forbidden exception. It's a simple entry having a title, content and a date range. Code snippet provided below;
public void temp() {
URL postURL = null;
try {
    postURL = new URL("http://www.google.com/calendar/feeds/MAILID@gmail.com/PASSWORD/full");
    EventEntry eventEntry = new EventEntry();
    eventEntry.setTitle(new PlainTextConstruct("One"));
    eventEntry.setContent(new PlainTextConstruct("Two"));

    When eventTime = new When();
    eventTime.setStartTime(DateTime.parseDateTime("2016-03-09T15:00:00-08:00"));
    eventTime.setEndTime(DateTime.parseDateTime("2016-03-09T15:00:00-08:00"));
    eventEntry.addTime(eventTime);

    CalendarService calendarService = new CalendarService("Savor");
    EventEntry createdEvent = calendarService.insert(postURL, eventEntry);
} catch (Exception e) {
    e.printStackTrace();
}

}
While doing this, I am getting ServiceForbidden exception provided below[Please ignore the line numbers shown in exception]
    com.google.gdata.util.ServiceForbiddenException: Forbidden

<TITLE>Forbidden</TITLE>

Forbidden

Error 403

    at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:605)
    at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
    at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
    at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
    at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
    at com.google.gdata.client.Service.insert(Service.java:1409)
    at com.google.gdata.client.GoogleService.insert(GoogleService.java:613)
    at GCalender.temp(GCalender.java:68)
    at GCalender.main(GCalender.java:85)

Exception occurs in this line: EventEntry createdEvent = calendarService.insert(postURL, eventEntry);
Trying to resolve this but sort of stucked up at this point. If anyone has came across this already, please provide your inputs, would be a great help..
Thanks!!
PS: Pls. ignore if the question is tagged with incorrect tag entries.

A: You are using Google Calendar API v2 which is Shut down.  You need to switch to Google Calendar v3
Documentation for Events: insert
event = service.events().insert(calendarId, event).execute();

Update:
Your code has the following
MAILID@gmail.com/PASSWORD/

You need to also be aware that accessing Google APIs using a login and password no longer works.  Client login was also shut down.  You will need to Authenticate your application using Oauth2.


text:
Q: Overwrite elements of list in R after adding missing column For a list of data frames, I would like to check if a column is present and if it's not, add that column with NA's to all data frames. Most importantly, I am trying to overwrite the old data frames.
Datasets:
df1 <- data.frame(a=c(1,2), b=c(3,NA))
df2 <- data.frame(b=c(1,2), c=c(3,NA))
df_list=list(df1, df2)
name <- "a"

My attempt:
df_list <- lapply(df_list, function(x) x[name[!(name %in% colnames(x))]] = NA)

I am looking for this result:
> df_list
[[1]]
  a  b
1 1  3
2 2 NA

[[2]]
  b  c  a
1 1  3 NA
2 2 NA NA

A: I would use a for loop to modify the data frames in place:
for(i in seq_along(df_list)) {
  if(!name %in% names(df_list[[i]])) {
    df_list[[i]][[name]] = NA
  }
}

You could take a similar approach with lapply, but in this case I find the for loop easier to understand. We need to make sure the lapplied function returns the data frame--either modified or as-is (this is the main difference from your attempt).
df_list = lapply(df_list, function(x) {
  if(! name %in% names(x)) {
    x[[name]] = NA
  }
  return(x)
})

A: I would suggest a similar approach like @GregorThomas but using vectors to save the results of those dataframes which do not contain the variable and then with lapply() you can create the desired variable:
#Data
df1 <- data.frame(a=c(1,2), b=c(3,NA))
df2 <- data.frame(b=c(1,2), c=c(3,NA))
df_list=list(df1, df2)
name <- "a"
#Check
x <- sapply(df_list,function(x) length(which(names(x)==name)))
y <- which(x==0)
#Format new list
df_list[y] <- lapply(df_list[y],function(x) {x[[name]]<-NA;return(x)})

Output:
df_list

[[1]]
  a  b
1 1  3
2 2 NA

[[2]]
  b  c  a
1 1  3 NA
2 2 NA NA

A: Modifying you code - what was missing was to return the updated x or using setdiff.
#lapply(df_list, function(x) x[name[!(name %in% colnames(x))]] = NA) #Your original code
lapply(df_list, function(x) {x[name[!(name %in% colnames(x))]] = NA; x}) #Modified
lapply(df_list, function(x) {x[,setdiff(name, names(x))] <- NA; x}) #Alternative
#[[1]]
#  a  b
#1 1  3
#2 2 NA
#
#[[2]]
#  b  c  a
#1 1  3 NA
#2 2 NA NA


text:
Q: How to configure apache cache expire setting for browser using ubuntu 16.04 I am unable to configure apache mod_cache to expire 1 day time downloaded content from the browser, Please suggest me how to do that.

A: The CacheDefaultExpire directive specifies a default time, in seconds, to cache a document if neither an expiry date nor last-modified date are provided with the document. The value specified with the CacheMaxExpire directive does not override this setting.
CacheDefaultExpire 86400 (seconds)


text:
Q: Insert missing newline characters when only CR is used I have a binary program that outputs intermediate results on the terminal and always rewrites that line. Internally, it probably uses something like system("echo -e '\rsome_useful_number').
So what I see and want to record is (sequentially):
data 1, data 2, data 3, ...
What I get when I run ./program | tee log.txt, ./program>log.txt, etc. as part of a script is just last_result.
How can I adapt my script to "insert" the missing newline characters?

A: The CR means "go back to the beginning of the current line".
Therefore the next line is overwriting the previous line. That means that all lines are there but only the last is visible.
Running less log.txt instead of cat log.txt should show you something like:
first_line^Mnext_line^Mlast_line

As @anubhava said:
./program | tr '\r' '\n' | tee log.txt or ./program | tr '\r' '\n' >log.txt will fix this before writing to the file, or just use cat log.txt | tr '\r' '\n' to view the file.
P.S.: Actually you should use tr '\r' '\n' < log.txt to avoid a UUoC-Award :)
Update:
When the program outputs to stderr the stderr has to be added to the stdout first:
./program 2>&1 | tr '\r' '\n' | tee log.txt

And finally if you want to keep the original CR output on the console's stderr:
./program 2>&1 | tee /dev/stderr | tr '\r' '\n' > log.txt


text:
Q: Openlayers - Vector Layer - Combining hide/show features using style property I am trying to filter vector layer features according to their attributes.
I have 4 check boxes: type_1, type_2, shape_1 and shape_2
Note that I am using Extjs for interface.
at beginning I could filter type attribute setting style to 'none' or '' ... like so :
switch (f) {
case 'type_1':
if(checked)
filter('show_type_1');
else filter ('hide_type_1);

case 'type_2':
if(checked)
filter('show_type_2');
else filter ('hide_type_2);

}

function filter(value)
{
 switch (value){

case 'hide_type_1':
for (i=0;i<=features.length;i++)
if(features[i].attributes.type == 'first')
features[i].style = 'none';
layer.redraw();

case 'show_type_1':
for (i=0;i<=features.length;i++)
if(features[i].attributes.type == 'first')
features[i].style = '';
layer.redraw();

case 'hide_type_2':
for (i=0;i<=features.length;i++)
if(features[i].attributes.type == 'second')
features[i].style = 'none';
layer.redraw();

case 'show_type_2':
for (i=0;i<=features.length;i++)
if(features[i].attributes.type == 'second')
features[i].style = '';
layer.redraw();

}
}

all above works great, if I uncheck type_1, all type_1 features will diappear.
then if I uncheck type_2, all type_2 features will diappear.
then if I check type_1 again, all type_1 features will appear, and type_2 features will stay hidden.
The problem is when I tried to do the same with shape attribute, by adding:
case 'shape_1':
if(checked)
filter('show_shape_1');
else filter ('hide_shape_1);

to the first function.
and:
case 'hide_shape_1':
for (i=0;i<=features.length;i++)
if(features[i].attributes.shape == 'first')
features[i].style = 'none';
layer.redraw();

case 'show_shape_1':
for (i=0;i<=features.length;i++)
if(features[i].attributes.shape == 'first')
features[i].style = '';
layer.redraw();

to the second one.
it works when I uncheck the shape_1 checkbox. all shape_1 features hid. but if check it to display them, all features will be displayed even type_1 and type_2  which I was keeping them unchecked and hidden!
I don't understand why that happens. because it works fine if I handle one attribute (type in my case) but failed when tried to combine type filtering with another feature attribute (shape).
I hope my explanation is clear.

A: Why don't you try using the style features of the Vector layers in combination with the rules, looks like what you are trying to do yourself can be done already, you create 2 styles, one standard, one temp , which is what you typically use when the feature is hovered.
  var halte_temp_styled = new OpenLayers.Style({
      fillColor: "red",
      fontColor: "#000000",
      fontWeight: "normal",
      pointRadius: 8,
      fontSize: "11px",
      strokeColor: "#ff9933",
      strokeWidth: 2,
      pointerEvents: "all",
      fillOpacity: 0.3,
      label : "${name}",
      labelOutlineColor: "white",
      labelAlign: "rb",
      labelOutlineWidth: 8,
      cursor: "pointer",
      fontFamily: "sans-serif"
   });

  var halte_styled = new OpenLayers.Style({
      fillColor: "red",
      fillOpacity: 0.6,
      fontColor: "#000000",
      fontWeight: "light",
      pointRadius: 8,
      fontSize: "11px",
      strokeColor: "#ff9963",
      strokeWidth: 3,
      pointerEvents: "all",
      labelOutlineColor: "white",
      labelOutlineWidth: 8,
      labelAlign: "cm",
      cursor: "pointer",
      fontFamily: "sans-serif"
   });

   var halte_style = new OpenLayers.StyleMap({
      'default' : halte_styled,
      'temporary' : halte_temp_styled
   });

Then add the rules , who will influence the behavior of the (default) style, in the example below it will follow the scale of the layer and act accordingly.  In this example, once you are zoomed at level 18, the labels of the feature will be displayed, else they will only be displayed when hovered over.
/* Style the halte layer acc to res */
   halte_style.styles['default'].addRules([
         new OpenLayers.Rule({
         maxScaleDenominator: 215000,
         minScaleDenominator: 27000,
         symbolizer: {
            fillColor: "red",
            fillOpacity: 0.6,
            fontColor: "#000000",
            fontWeight: "light",
            pointRadius: 4,
            fontSize: "11px",
            strokeColor: "#ff9963",
            strokeWidth: 2,
            pointerEvents: "all",
            labelOutlineColor: "white",
            labelOutlineWidth: 8,
            labelAlign: "cm",
            cursor: "pointer",
            fontFamily: "sans-serif"

            }
         }),

      new OpenLayers.Rule({
         maxScaleDenominator: 27000,
         minScaleDenominator: 3384,
         symbolizer: {
            fillColor: "red",
            fillOpacity: 0.6,
            fontColor: "#000000",
            fontWeight: "light",
            pointRadius: 10,
            fontSize: "11px",
            strokeColor: "#ff9963",
            strokeWidth: 3,
            pointerEvents: "all",
            labelOutlineColor: "white",
            labelOutlineWidth: 8,
            labelAlign: "cm",
            cursor: "pointer",
            fontFamily: "sans-serif"

            }
         }),
      new OpenLayers.Rule({
         maxScaleDenominator: 3384,
         minScaleDenominator: 1,
         symbolizer: {
            fillColor: "red",
            fillOpacity: 0.6,
            fontColor: "#000000",
            fontWeight: "light",
            pointRadius: 10,
            fontSize: "11px",
            strokeColor: "#ff9963",
            strokeWidth: 3,
            label : "${name}",
            labelAlign: "cm",
            //labelAlign: "cm",
            pointerEvents: "all",
            labelOutlineColor: "white",
            labelOutlineWidth: 8,
            cursor: "pointer",
            fontFamily: "sans-serif"
            }
         })
      ]);

In the vector layer in question you set this stylemap:
    styleMap: halte_style,

I'm not sure if this helps you specifically , but when I read this, I remembered I tackled this before by using style/rules on vector layers.  Hope this at least gives an alternative to staring at the same problem for days instead.

A: Try this:
// set style
    features[i].style = null;
// or
    features[i].style = {display:'none'};

// redraw feature
layer.drawFeature(features[i]);


text:
Q: Not understanding the behavior of the float and overflow attributes

.title-strip{
  background: green;
  margin: 0;
  }
.title1 {
  overflow: hidden;
  }
.title2 {
  float: right;
  }

Title1

Title2

.title-strip {
  background: green;
  margin: 0;
}

.title1 {
  overflow: hidden;
}

.title2 {
  float: right;
}

Title2

Title1

If the first h1 tag has the title1 class and the second has the title2 class, the text is on different lines.
But when the classes are swapped, the text is on separate lines. Why?
I read a stack overflow answer saying that 'BFCs don't allow descendant floats to escape them, nor do they allow sibling/ancestor floats to intrude into them', the result of words in the same line seems to go against this.
Am I wrong?

A: welcome to stackoverflow. Overflow: hidden makes no difference (please know this). When you use the float property on an item, it acts as inline-block even if it is block. In the example you have done here, the line in which it is located (the line it can go to) leans to the right and remains inline block.
I changed the colors so you could see more clearly. Please examine both samples carefully. in the first example, first the float right element is used, then the block element is used because they switch to the inside. But if the block element is used first then it continues from the bottom line without covering an area.
A small note: Float is no longer used frequently today. Instead, I suggest you choose structures such as display-flex or display-grid. They are both simpler and more useful for responsive appearance. I hope the description what I mean.

.title-strip {
  background: green;
  margin: 0;
}

.title1 {
  /* overflow: hidden;   it doesn't make any difference. */
  background-color: yellow;
}

.title2 {
  float: right;
  background-color: red;
}

Title2

Title1

Title2

Title1

Title2

Title1

A:
I read a stack overflow answer saying that 'BFCs don't allow descendant floats to escape them, nor do they allow sibling/ancestor floats to intrude into them',

This is true not when the overflow is applyied to the float element but when the float element is inside the element where overflow is applyied
Here is a basic example to understand:

.title-strip {
  background: green;
  margin: 0;
}

.title1 {
  background: red;
}

.title2 {
  float: right;
}

Title2

Title1

Title2

Title1

See how in the second case the floated title is no more on the right of non-floated one because it's inside a div with overflow:hidden. It's own BFC so it no more interact with anything outside.


text:
Q: touchesEnded:withEvent: not detecting the top node in SpriteKit I have a custom class Object derived from SKSpriteNode with an SKLabelNode member variable.
#import <SpriteKit/SpriteKit.h>

@interface Object : SKSpriteNode {
    SKLabelNode* n;
}

@end

In the implementation, I set up the SKLabelNode.
#import "Object.h"

@implementation Object

- (instancetype) initWithImageNamed:(NSString *)name {
    self = [super initWithImageNamed:name];

    n = [[SKLabelNode alloc] initWithFontNamed:@"Courier"];
    n.text = @"Hello";
    n.zPosition = -1;
    //[self addChild:n];

    return self;
}

Note: I have not yet added the SKLabelNode as a child to Object.  I have the line commented out.
I have a separate class derived from SKScene.  In this class, I add an instance of Object as a child. This is my touchesBegan:withEvent: method in this class:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch = [touches anyObject];
    CGPoint loc = [touch locationInNode:self];
    NSArray* nodes = [self nodesAtPoint:loc]; //to find all nodes at the touch location
    SKNode* n = [self nodeAtPoint:loc]; //to find the top most node at the touch location

    NSLog(@"TOP: %@",[n class]);
    for(SKNode* node in nodes) {
        NSLog(@"%@",[node class]);
    }
}

When I tap on the instance of Object in my SKScene class, it works as I expected. It detects the node is an instance of Object. It logs:
TOP: Object
Object

Now if I go back to my Object class and uncomment [self addChild:n] so that the SKLabelNode is added as a child to Object, this is logged:
TOP: SKLabelNode
Object
SKLabelNode
SKSpriteNode

Why does adding an SKLabelNode as a child to a class derived from SKSpriteNode cause the touch to detect the object itself, along with an SKLabelNode and an SKSpriteNode?
Furthermore, why is the SKLabelNode on top? I have its zPosition as -1 so I would assume that in touchesBegan:withEvent: of another class, the Object would be detected as on top?
Surely, I am not understanding an important concept.

A: If you use nodeAtPoint to check for the node in -touchesEnded:, it will definitely return the topmost node at the point of the touch, which in this case, is the SKLabelNode. There are a few ways you can go around this:

Making the subclass detect it's own touches
The cleanest way would be to make the Object subclass detect it's own touches. This can be done by setting it's userInteractionEnabled property to YES. This can be done in the init method itself.
-(instanceType) init {
    if (self = [super init]) {
        self.userInteractionEnabled = YES;
    }
    return self;
}

Now, implement the touch delegate methods in the class itself. Since the LabelNode has its userInteractionEnabled property set by default as NO, the touch delegates will still be triggered when it is tapped.
You can use either delegation, NSNotificationCenter or a direct message to the parent in the touch delegate.
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    //Send a message to the delegate, which is the SKScene, should be included in protocol
    [self.delegate handleTouchOnObjectInstance:self];

    //or, send a message directly to the SKScene, the method should be included in the interface.
    MyScene *myScene = (MyScene*)self.scene;
    [myScene handleTouchOnObjectInstance:self];
}

Checking for the node's parent
In the touch delegate of the SKScene, you can check whether the parent node of the SKLabelNode returned from nodeAtPoint is an instance of the C class.
//Inside the touch delegate, after extracting touchPoint
SKNode *node = [self nodeAtPoint: touchPoint];

if ([node isKindOfClass: [SKLabelNode class]]) {
    if ([node.parent isKindOfClass: [Object class]])
        [self performOperationOnCInstance: (Object*)node.parent];
} else if ([node isKindOfClass: [Object class]])
    [self performOperationOnCInstance: (Object*)node];

Use nodesAtPoint instead of nodeAtPoint
This method returns an array of all nodes detected at a certain point. So if the SKLabelNode is tapped, the nodesAtPoint method will return the Object node as well.
//Inside the touch delegate, after extracting touchPoint
NSArray *nodes = [self nodesAtPoint: touchPoint];

for (SKNode *node in nodes) {
    if ( [node isKindOfClass: [Object class]]) {
        [self performOperationOnObjectInstance: (Object*)node];
        break;
    }
}

EDIT:
There is a difference between the zPosition and the node tree.
The zPosition only tells the scene to render nodes in a certain order, whatever their child order may be. This property was introduced to make it easier to specify the order in which a node's children are drawn. If the same were to be achieved by adding the nodes to the parent in a specific order, it becomes difficult to manage the nodes.
When the nodesAtPoint method is called, the scene conducts a depth-first search through the node tree to see which nodes intersect the given touch point. This explains the order in which the array is populated.
The nodeAtPoint method returns the deepest node according to zPosition which the scene could find.
The following section from Apple's documentation explains it all extensively: Creating The Node Tree


text:
Q: windows: is there any way to drop into command line terminal when explorer freezes completely? Lately I have had issues with Windows explorer freezing completely (i.e. mouse is stuck in busy icon and you can not click anywhere and you can not do keyboard shortcuts to pull up task-manager or ctrl-alt-delete).
In Linux, when this happens there is a simple fix you drop into command line terminal via ctrl-alt-F2 or ctrl-alt-F3 and then from the command line terminal you can fix the problem or at least reboot the machine gracefully.

*

*Fix the problem: From the command line terminal you can find fix the issue by finding the stuck process and killing the process and then go back to normal processing.

*Reboot the machine gracefully: Sometimes you can not fix the issue but you can at least tell the machine to reboot (which can in many cases save files from being corrupted like raid-1 drive from needing to be rebuilt).

In windows, is there any way to drop into command line terminal when explorer freezes completely?
If there is not any way to drop into the command line terminal, is there any way to recover without hard power cycle?


text:
Q: how can you tell a real e-mail from a fake? I used to get emails from this guy possibly pretending to be a friend of mine (using an AIM account rather than his GMAIL one). Things were going OK with email tramsmisions but now everytime I send, they come back as MAILER DAEMON
is there any possible way to tell where those email originated from.....after I deleted the emails that went through?

A: email information is stored in email's header. If you don't the the emails anymore, you won't be able to tell where did they come from.


text:
Q: How to check preceding character of a RegEx search pattern using PHP? I would like to check if the preceding character of a search pattern is an alphanumeric character.
If true, do nothing.
If fasle, remove the preceding space in the search pattern.
For example:
$string1 = "This is a test XYZ something else";

$string2 = "This is a test? XYZ something else";

$pattern = " XYZ";

In $string1 scenario, the preceding character of the search pattern is t and considered a match, nothing will be perform.
In $string2 scenario, the preceding character of the search pattern is ? and considered a non-match, and I'm removing the extra space in searhc pattern.
Making it:
$string2 = "This is a test?XYZ something else";

How can this be accomplished in PHP?

A: You may use a \B XYZ pattern and use a preg_replace_callback to trim the match value and insert it back:
$string1 = "This is a test XYZ something else";
$string2 = "This is a test? XYZ something else";
$pattern = " XYZ";
echo preg_replace_callback('~\B'.$pattern.'~', function($m) { return trim($m[0]); }, $string1) . PHP_EOL;
// => This is a test XYZ something else
echo preg_replace_callback('~\B'.$pattern.'~', function($m) { return trim($m[0]); }, $string2);
// => This is a test?XYZ something else

See the PHP demo
Since \B matches at the locations other than those matched with a word boundary (a non-word boundary), the pattern \B XYZ will only match after a non-word char.
More details: your pattern starts with a space. This is a non word char. By adding \B before it we require that the character before the space should also be a non word char. Else, we'll get no match. The word char is a char from [a-zA-Z0-9_] range. If you need to customize the boundary, use a lookbehind like (?<![a-zA-Z0-9]) to exclude the underscore from the boundary characters.
For more information on non-word boundary see this What are non-word boundary in regex (\B), compared to word-boundary? SO thread.


text:
Q: What are the advantages of normalizing a database? I really cant get a good solid understanding of this. I see a lot of examples in the internet but lacking explanation on why. For example, you have two kinds of users in an application, a customer and a manager. What are the advantages of creating a separate "user_type" table instead of incorporating the "user_type" column in a user table. Another example is creating a separate table for a category of a product instead of putting the category field in the product table. I really can't get my head around this. What are the advantages of db normalization? And the disadvantages of duplicate data in a database?

A: The disadvantages of duplicate data is that you have to remember where all the copies of the data are and to update all of them when information is changed. Normalization is more about de-duplication than creating separate tables.
In your example of user_type, you can just put that in a column on the user table. The additional table comes in handy if the user can have multiple user types.

A: The stated purpose of normalization is to prevent anomalous data from getting into the database.
Such as, take a very simple user entity:
create table Users(
  ID        int auto_generated primary key,
  LastName  varchar( 16 ) not null,
  FirstName varchar( 16 ) not null
);

Now it turns out there can be two types of users: Manager (M) or Peon (P). Also, for managers, we need to know how many people directly report to them and for peons, we need to know if they have a forklift license. Let's just throw that into the table:
create table Users(
  ID           int auto_generated primary key,
  LastName     varchar( 16 ) not null,
  FirstName    varchar( 16 ) not null,
  UserType     char( 1 ) not null,
  DirectReps   int,
  HasFLLicense boolean
);

This should start all kinds of alarms going off in your head. What can go wrong?

*

*The only valid values for UserType (at this point) are 'M' or 'P'. This field, however, can contain any single character. We can create a "check" on this column, but that will create another problem which I will cover later.

*The DirectReps and HasFLLicense fields are only applicable if the UserType field contains 'M' or 'P' respectively. There is no way to enforce this internally -- it would have to be done with triggers and/or app code.

There are no easy ways to enforce these new constraints. And we all know that no matter how careful we are, sooner or later we will have UserType values other than 'M' or 'P' and/or values in DirectReps or HasFLLicense inappropriately. This is anomalous data.
If you look closely, the fields LastName, FirstName and UserType has a functional dependency only on ID. However, DirectReps and HasFLLicense are also dependent on UserType. This new table is not in 2nf.
Normalizing this table can be done is several different ways so I won't go into that. (Here is one method I presented earlier today.) Needless to say, the end result should be done so that a DirectReps value cannot exist unless the UserType value is 'M' and a HasFLLicense value cannot exist unless the UserType value is 'P'.
Now let's look at just the normalized table:
create table Users(
  ID           int auto_generated primary key,
  LastName     varchar( 16 ) not null,
  FirstName    varchar( 16 ) not null,
  UserType     char( 1 ) check( UserType in( 'M', 'P' )
);

There are some normalization methods that would also remove the UserType field from the table but let's leave it here for now. The following applies no matter where it is located.
The problem appears when you consider that, sooner or later, a third type will be required. And at different points another and then another and you get the idea. Each time we would have to issue an alter table command just to rewrite the check constraint. This is like completely demolishing and rebuilding your home just to replace your living room sofa. All the code that accesses this table (including views) would have to be, at a minimum, recompiled and possibly rewritten. Let's face it, alter table is a non-trivial operation.
How much better to have a lookup table containing a record for every user type:
create table UserTypes(
  ID      char( 1 ) not null primary key, -- 'M' or 'P' or whatever
  Name    varchar( 16 ) not null,  -- "Manager" or "Peon" or whatever
  ...     -- other possible attributes
);

Then the UserType field may be defined:
  UserType     char( 1 ) not null references UserTypes( ID )

Now adding a type 'A' or 'F' or whatever is simply a matter of inserting a record into the UserTypes table. Existing code is unaffected. Of course, the app code will ultimately have to be changed to handle the new types, but the app developers can do this now at their leisure.
Don't just design for current requirements. Also design for reasonably expected future requirements.


text:
Q: Mysql Rollback Restore A colleague from my office created a backup of MySql database of different location and mistakenly he restored the same to another location server, which had overwritten existing data.
Is there any possibilities to rollback the restore and get the old data back?
Even the backup of that database got corrupted, hence we are not able to restore that again.


text:
Q: Hive - Column Found in more than One Tables/Subqueries I need to create a table in Hive that have multiple sub-queries. The query is:
CREATE TABLE table AS
select dense_rank() OVER (ORDER BY Client) AS Client,
       A.STORE,
       from_unixtime(unix_timestamp(A.DATE_Client , 'yyyy-MM-dd')) AS Date_Client,
      year(A.DATE_Client) as YEAR_Client,
       (INT((MONTH(A.DATE_Client)-1)/3)+1) as QUARTER_Client,
       MONTH(A.DATE_Client) as MONTH_Client,
       weekofyear(A.DATE_Client) as WEEK_Client,
       DAY(A.DATE_Client) as DAY_Client,
       from_unixtime(unix_timestamp(A.DATE_Client , 'yyyy-MM-dd'),'u') as WeekDay,
       b.Last_Visit,
       A.transaction_value/A.transaction_Quantity AS PRODUCT_VALUE
from (select e.*,
            tb1.seqnum
      from (SELECT Distinct d.STORE as STORE_rank,DENSE_RANK() over (order by d.STORE, RAND()) as seqnum from staging_area d) tb1
      join staging_area e
      on tb1.STORE_rank = e.STORE
     ) A
JOIN (SELECT Client, MAX(DATE_Client) AS Last_Visit
            FROM LAST_VISIT
            GROUP BY Client) B
ON A.Client = B.Client
where seqnum < 41 and Date_Client >= '2013-01-01' and Date_Client <= '2013-30';

However, when I try to run this I'm getting the following error:
Error while compiling statement: FAILED: SemanticException Failed to breakup Windowing invocations into Groups. At least 1 group must only depend on input columns. Also check for circular dependencies. Underlying error: org.apache.hadoop.hive.ql.parse.SemanticException: Column client Found in more than One Tables/Subqueries

Anyone knows how can I solve this?
Many thanks!


text:
Q: Change hash suffix on build using react I'm using React JS and when I build my app to deploy, I use react-scripts as follow below:
react-scripts build

And my chunk files are something like:
0.cebdafcf.chunk.js
1.fa48de00.chunk.js
2.98b9bea7.chunk.js
...
52.9ca2408d.chunk.js
App.7b21e172.chunk.js
dashboards.f6142b89.chunk.js
user-forgot-password.06d87a22.chunk.js
views.16dc12b2.chunk.js
...

But every time I build, the hash suffix are the same, for example, I'd like every build change the hash for App..chunk.js
Is there any way to do it?
I've tried the option described here: Github Renamer Answer, using the lib renamer, but it didn't work to update the hash name for all chunk files.
Thank you in advance for helping

A: What I've done to solve was: First of all, I had to eject react so on this way I had access to change the webpack.config and after I've changed on webpack.config everything with
[contenthash:8]

to
[contenthash]

So, on this way, everytime we have a change on the file, the hash config chunk will be different. And for me, it's enough.
I don't know if someone has another solution, better or simpler. If yes, post to help other people.