text:
Q: why countdown counter with thread show wrong value? I don't know why this count down counter shows a random number at the end?
I mean that it sometimes shows 60:15, sometimes 60:07, so on this way
min=sec=0;
new Thread(new Runnable() {
    @Override
    public void run() {
        while (min < 60  && flagTime) {
            try {
                Thread.sleep(1);
                G.HANDLER.post(new Runnable() {
                    @Override
                    public void run() {
                        String preSec="";
                        String preMin="";
                        if (sec < 59) {
                            sec += 1;
                        }
                        if (sec < 10) {
                            preSec = "0";
                        }
                        if (min < 10) {
                            preMin = "0";
                        }
                        score =preMin + min + ":"
                                + preSec + sec;
                        txt[elementNumber + 1].setText(score);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}).start();

Please someone tell me why it works so weird?

A: Timing in ALL OSes is NOT precise, unless you use a framework or tools that is already designed for this task. You can however work with Thread.Sleep with a reasonable uncertainty. But for "reasonable" and "precise" timing, it depends on the problem you are trying to solve.
In threads, sleep(1000) does not mean that the thread will sleep exactly 1 second, so that the thread will sleep less or more every time you run your app. that is why you get random results.
This has many things else to consider like the priority of the thread.
so a better way to count down is to use other ways which is provided by android:
CountDownTimer
Timer
you may check on google and you will find many examples about how to use them.
those are more reliable and more precise.
hope this helps.

A: The likely reason that you're getting weird results in your TextView is that you're updating it from a thread that is not the main UI thread.
But you're making this harder than it needs to be. An easier approach would be to use a simple CountDownTimer object like this:
final long SECS_IN_1_MIN = 60;
final long MILLIS_IN_1_SEC = 1000;
final long MILLIS_IN_60_MINS = 3600000;

final TextView timer = (TextView) findViewById(R.id.timer);
new CountDownTimer(MILLIS_IN_60_MINS, MILLIS_IN_1_SEC) {
    public void onTick(long millisUntilFinished) {
        if (flagTime) {
            long secs = (MILLIS_IN_60_MINS - millisUntilFinished) / MILLIS_IN_1_SEC;
            timer.setText(String.format("%02d:%02d", secs / SECS_IN_1_MIN, secs % SECS_IN_1_MIN));

        } else {
            timer.setText("cancelled");
            cancel();
        }
    }

    public void onFinish() {
        timer.setText("time expired");
    }
}.start();

Edit: It uses a CountDownTimer to handle the timing, while using its  millisUntilFinished value to calculate and display what appears to be an increasing seconds count. I threw in some symbolic names to make the code clearer and a String.format to handle single digit values in a more elegant fashion. Enjoy!


text:
Q: Observable periodically pause then continue How to pause observable every 15 seconds then wait for 5s and then continue emitting?
I made this example:
const digits = interval(1000);
const pauser$ = interval(20000).pipe(mapTo(true));
pauser$.subscribe(item =>
  console.log(`${new Date().toISOString()} pause fired`)
);
const pauseStopper$ = pauser$.pipe(
  concatMap(_ => timer(5000)),
  tap(() => console.log(`${new Date().toISOString()} pause stopped`)),
  mapTo(false)
);

const observable = merge(pauser$, pauseStopper$).pipe(
  startWith(false),
  switchMap(paused => (paused ? NEVER : digits))
);

observable.subscribe(
  item => console.log(`${new Date().toISOString()}: ${item}`),
  console.error,
  () => console.log("complete")
);

After first pause cycle it behaves nearly close to what I need. Any ideas on how to make this more clear?
stackblitz example

A: I created a player function that gets three params:

*

*source$: Your source observable that should be paused/played

*play$: Continues to emit your source$ observable

*pause$: Pauses your source$ observable

const player = <T>(source$: Observable<T>, play$: Observable<void>, pause$: Observable<void>): Observable<T> =>
  merge(
    play$.pipe(
      switchMap(() => of(source$))
    ),
    pause$.pipe(
      switchMap(() => of(NEVER))
    )
  ).pipe(
    switchMap(stream => stream)
  )

This function currently throws an error as far as I can see. In the short time I have atm I could not fix the error. The error is caused by of(void 0) in the pause$ switchMap. Later I will try to fix this error. Forfeit the error the function works.
You can now use a play$ and pause$ Observable to emit the play/pause:
const play$: Observable<void> = interval(20000).pipe(
  startWith(void 0),
  mapTo(void 0)
);

const pause$: Observable<void> = play$.pipe(
  switchMap(() => interval(15000).pipe(
    take(1)
  )),
  mapTo(void 0)
);

const player$ = player(source$, play$, pause$);

Does this solve your problem? If there are any issues with the solution let me know and I try to adapt.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to tell Three.js not to use interpolation when zooming an object's texture? It is a plane with a sprite art as texture so I'd like it zoomed using no interpolation method.

A: You can get no interpolation like this:
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.NearestFilter;

However, if you're after a minecraft look where there is interpolation in the far areas (less noisy), you'll need this combo:
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.LinearMipMapLinearFilter;


text:
Q: Download a file from an s3 bucket with REST I am attempting to download from an s3 bucket with REST calls. I am able to create buckets, delete buckets and list buckets. Downloading always ends with either an object not found or HTTP response code: 403. The code is below. Also does anyone know if amazon was sdk can be used with non amazon sites?
public void getObject() throws Exception
{
String fmt = "EEE, dd MMM yyyy HH:mm:ss ";
    SimpleDateFormat df = new SimpleDateFormat(fmt, Locale.US);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    String ob2 = "/bucket/test.txt";
    String bucket = "/bucket";
    String method = "GET";
    String contentMD5 = "";
    String contentType = "";
    String date = df.format(new Date()) + "GMT";

    // Generate signature
    StringBuffer buf = new StringBuffer();
    buf.append(method).append("\n");
    buf.append(contentMD5).append("\n");
    buf.append(contentType).append("\n");
    buf.append(date).append("\n");
    buf.append(ob2);
    String signature = sign(buf.toString());

    HttpURLConnection httpConn = null;
    URL url = new URL("https","s3demo.s3demosite.com",443,bucket);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setDoInput(true);
    httpConn.setDoOutput(true);
    httpConn.setUseCaches(false);
    httpConn.setDefaultUseCaches(false);
    httpConn.setAllowUserInteraction(true);
    httpConn.setRequestMethod(method);
    httpConn.setRequestProperty("Date", date);
    httpConn.setRequestProperty("Content-Length", "0");
    String AWSAuth = "AWS " + keyId + ":" + signature;
    httpConn.setRequestProperty("Authorization", AWSAuth);

    // Send the HTTP PUT request.
    int statusCode = httpConn.getResponseCode();
    InputStream err = httpConn.getErrorStream();
    InputStream is = null;
    is = httpConn.getInputStream();
    int ch;
    StringBuffer sb = new StringBuffer();
    while ((ch = err.read()) != -1) {
      sb.append((char) ch);
    }
    if ((statusCode/100) != 2)
    {
        // Deal with S3 error stream.
        InputStream in = httpConn.getErrorStream();
        System.out.println("Error: "+errorStr);
    }
    else
    {
        System.out.println("download worked");
    }
}


text:
Q: check if file exist i want to check a folder.if i found "test.jpeg" in "path" if it 's true i do nothing but if it false i have to download this picture like that
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dico objectForKey:@"photo"]]]];
nomPhoto = [[cell.pseudo text]stringByReplacingOccurrencesOfString:@"\n" withString:@""];;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *document = [paths objectAtIndex:0];
filename = [NSString stringWithFormat:@"%@/%@.jpeg",document,nomPhoto];

NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.1f)];//1.0f = 100% quality

[data2 writeToFile:filename atomically:YES];

EDIT: i try this but don't work. the path is good
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* pict =  [documentsPath stringByAppendingPathComponent :@"portos"];

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:pict];

if (fileExists)
{
    NSLog(@"file ok");
}else {
    NSLog(@"file ko");
}

thx

A: If the file specified doesn't exist the CGImage property of UIImage will be nil.
if (image.CGImage) NSLog(@"file ok");
else NSLog(@"file ko");

A: Its already answered here.
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:somePath];


text:
Q: rcdimple facet function subplot labels I am using rcdimple to create a set of faceted barplots based on a categorical column. The plots are coming out as expected but I cannot figure out how to apply a label to each subplot.
In the example below I have commented out some of the options I have tried:
fake.data <- read.table(sep=',', header=T, text="
    category,variable,value,count
    A Category,SITE.ACTIVITIES,1,51
    A Category,SITE.ACTIVITIES,2,116
    A Category,SITE.ACTIVITIES,3,46
    A Category,PROXIMITY.TO.RECEPTORS,1,17
    A Category,PROXIMITY.TO.RECEPTORS,2,111
    A Category,PROXIMITY.TO.RECEPTORS,3,93
    All Others,SITE.ACTIVITIES,1,60
    All Others,SITE.ACTIVITIES,2,37
    All Others,SITE.ACTIVITIES,3,54
    All Others,PROXIMITY.TO.RECEPTORS,1,80
    All Others,PROXIMITY.TO.RECEPTORS,2,167
    All Others,PROXIMITY.TO.RECEPTORS,3,120
    ")

plt <- fake.data %>%
    dimple(x ="value", y = "count",
           #title = c('A Category','All Others'),
           groups = 'category', type = "bar",
           width = 900, height = 220) %>%
        facet('variable',
              #title = c('A Category','All Others'),
              removeAxes = T) %>%
        default_colors(c('blue','grey')) %>%
        xAxis(type = "addCategoryAxis",
              #facet.title = c('A Category','All Others'),
              orderRule = "value") %>%
        yAxis(overrideMax=300, ticks=4) %>%
        add_legend() %>%
        add_title(text = c('A Category','All Others'))

After seeing figure 2.14 in this blog post I have added the following:
plt$x$options$tasks <- list(htmlwidgets::JS('
  function(){
       //this.widgetDimple should hold our chart
       var chart1 = this.widgetDimple[0];
       var chart2 = this.widgetDimple[1];
       chart1.svg.append("text")
       .attr("x", chart1.axes[0]._scale(3) )
       .attr("y", chart1.axes[1]._scale(300) )
       .attr("text-anchor", "middle")
       .text("A Category")
       chart2.svg.append("text")
       .attr("x", chart2.axes[0]._scale(3) )
       .attr("y", chart2.axes[1]._scale(300) )
       .attr("dy", "0.6em")
       .attr("text-anchor", "middle")
       .text("All Others")
       }
       '))
plt

I think I am on the right path but think there is probably a cleaner way to do this (sorry my javascript is not great).

A: The easiest solution seems to be to add text via svg.append("text") as outlined above. The rcdimple facet function creates an array of chart objects one for each subplot. In turn each subplot contains the information needed for each label accessible via OBJECT.data[0].variable.
The solution presented below will work for any number of facet chart objects. The numbers 1 and 350 relate to the x and y position of the labels related to the x and y axis values. These would need to be modified for different datasets
plt <- fake.data %>%
        dimple(x ="value", y = "count",
               groups = 'category', type = "bar",
               width = 900, height = 220) %>%
            facet('variable',removeAxes = T) %>%
            default_colors(c('blue','grey')) %>%
            xAxis(type = "addCategoryAxis",orderRule = "value") %>%
            yAxis(overrideMax=300, ticks=4) %>%
            add_legend() %>%
            add_title(text = 'Plot Title')

plt$x$options$tasks <- list(htmlwidgets::JS(sprintf('
    function(){
        var n = this.widgetDimple.length
        var variables = {};
        var subs = [];
        for (var i = 1; i <= n; ++i) subs.push("c"+i)
        for( var i = 0; i < n; i++) {
            var v = subs[i];
            variables[v] = this.widgetDimple[i]
            variables[v].svg.append("text")
            .attr("x", variables[v].axes[0]._scale(%s) )
            .attr("y", variables[v].axes[1]._scale(%s) )
            .attr("text-anchor", "left")
            .text(variables[v].data[0].variable)
        };
    }
    ', 1, 350)))
plt

There may be a more elegant solution, my JS is not great. Thanks to authors of the rcdimple package and the examples given here


text:
Q: I get an IOException in Butterknife viewbinder code I can't edit I am working in android studio, using the butterknife.jar. But right know it is throwing an IOException in uneditable code. I throw the exception in the code that calls the method like this:
@OnClick(R.id.testButton)
public void Test() throws IOException {
     dispatchMakeJson("Test" + System.currentTimeMillis(),Link, Title, Description);
}

But in the viewbinder it says it wants to throw the exception again.
Does anybody know what I have to do here?

A: See this:
http://sourcey.com/beautiful-android-login-and-signup-screens-with-material-design/
Without seeing more of your code I can't really help but this tutorial is quite comprehensive for butterknife so have a look through that to see if there are any irregularities in your code.


text:
Q: Python Flask app- leading zeros in TOTP error. (Python 2.7) I have written a python flask application in which app generate totp for validation. (Python 2.7)
I use onetimepass library to validate totp against the application secret.
code:
    json_data=request.get_json()
    my_token=json_data['OTP']
    is_valid = otp.valid_totp(token=my_token, secret=my_secret)

However the issue i am facing is whenever a totp comes with leading zeroes it turns into an Octal number.
OTP is always treated as incorrect and user is unable to login.
How can i preserve these leading zeroes in such case? any code snippets or guidance will be of much help.

A: Answer was simple as my_token was coming as string and i was converting it to a number. Adding this before converting to a number did the trick:
my_token.lstrip("0") #removes leading characters


text:
Q: Remotely calculating SHA or MD5 of a file via web service? For example.. say I have an application that uses a web service. I want the application to consume the web service, which basically just calculates the MD5 or SHA-whatever of the consuming application.
What's the best way to achieve this? The consuming application is ~10kb.

A: Something like this would do it:
var request  = (HttpWebRequest) WebRequest.Create("http://www.remote.com/file");
var response = (HttpWebResponse) request.GetResponse();
var stream = response.GetResponseStream();
var hasher = new SHA1CryptoServiceProvider();
foreach (byte b in hasher.ComputeHash(stream))
    hash += b.ToString("x2").ToLower();

Obviously wrap that up in using's appropriate to keep resources under control.


text:
Q: Firebase Phone Auth with React Native Expo So I have been trying to implement the firebase phone auth in my react native project. I followed this great tutorial linked below but was facing issues with changing the confirmation section to be in a different page instead of the phone number input and code input all being on the same page. I get an error stating the verificationId was not found as its being called in the previous page.
Tutorial Link
If anyone can help out out, that would be great.
Thanks
  const const Login  = () => {
  const navigation =useNavigation();
  const [phoneNumber, setPhoneNumber] = useState();

  const [verificationId, setVerificationId] = useState(null);
  const recaptchaVerifier = useRef(null);

    const sendVerification  = () => {
       try {
    const phoneProvider = new firebase.auth.PhoneAuthProvider();
    phoneProvider
   .verifyPhoneNumber(phoneNumber, recaptchaVerifier.current)
   .then(setVerificationId);
     } catch (error) {
   alert(error);
     }
     navigation.navigate('OTPScreen', { verificationId:
   verificationId})

     };
    return(

OTP screen
const const OTPScreen  = () => {

const verificationId = props.route.params.verificationId
 const [code, setCode] = useState('');

const confirmCode = () => {
  const credential =
  firebase.auth.PhoneAuthProvider.credential(
    verificationId,
    code
  );
  firebase
    .auth()
    .signInWithCredential(credential)
    .then((result) => {
      console.log(result);
      navigation.navigate('Home')

    });

    };
   return(

A: There are two possible solution I have implemented

*

*Pass your confirmation object as params to new screens and then use it for OTP confirmation.

*You can also save this confirmation object in global store like redux.

For solution 1
const [confirm, setConfirm] = useState(null);

  async function signInWithPhoneNumber(phoneNumber) {
    const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
    setConfirm(confirmation);
  }

Then navigate to your otp screen as
navigation.navigate('otpScreen', {confirm: confirm})

On your otpScreen get the confirm object as params (use appropriate syntax for functional or class component, whatever you are using)
Then
const confirm = props.route.params.confirm

async function confirmCode() {
    try {
      await confirm.confirm(code);
    } catch (error) {
      console.log('Invalid code.');
    }
  }

A: the full firebase phone authentication full code is check in android
import * as React from "react";
import { Text, View, TextInput, Button, StyleSheet, TouchableOpacity, Platform } from "react-native";
import { FirebaseRecaptchaVerifierModal } from "expo-firebase-recaptcha";
import * as firebase from "firebase";
try {
  firebase.initializeApp({
    apiKey: 'AIzaSyApGoaZVtoVTYnftHSbT9l7nDmDVUYJYpU',
      authDomain: 'playground-d4e7b.firebaseapp.com',
      databaseURL: 'https://playground-d4e7b.firebaseio.com',
      projectId: 'playground-d4e7b',
      storageBucket: 'playground-d4e7b.appspot.com',
      messagingSenderId: '903405300293',
      appId: '1:903405300293:web:c55227a2b8064da05d112c',
  });
} catch (err) {
  // ignore app already initialized error in snack
}

export default function App() {
  const recaptchaVerifier = React.useRef(null);
  const [phoneNumber, setPhoneNumber] = React.useState();
  const [verificationId, setVerificationId] = React.useState();
  const [verificationCode, setVerificationCode] = React.useState();
  const firebaseConfig = firebase.apps.length ? firebase.app().options : undefined;
  const [message, showMessage] = React.useState((!firebaseConfig || Platform.OS === 'web')
    ? { text: "To get started, provide a valid firebase config in App.js and open this snack on an iOS or Android device."}
    : undefined);

  return (
    <View style={{ padding: 20, marginTop: 50 }}>
      <FirebaseRecaptchaVerifierModal
        ref={recaptchaVerifier}
        firebaseConfig={firebaseConfig}
      />
      <Text style={{ marginTop: 20 }}>Enter phone number</Text>
      <TextInput
        style={{ marginVertical: 10, fontSize: 17 }}
        placeholder="+1 999 999 9999"
        autoFocus
        autoCompleteType="tel"
        keyboardType="phone-pad"
        textContentType="telephoneNumber"
        onChangeText={(phoneNumber) => setPhoneNumber(phoneNumber)}
      />
      <Button
        title="Send Verification Code"
        disabled={!phoneNumber}
        onPress={async () => {
          // The FirebaseRecaptchaVerifierModal ref implements the
          // FirebaseAuthApplicationVerifier interface and can be
          // passed directly to `verifyPhoneNumber`.
          try {
            const phoneProvider = new firebase.auth.PhoneAuthProvider();
            const verificationId = await phoneProvider.verifyPhoneNumber(
              phoneNumber,
              recaptchaVerifier.current
            );
            setVerificationId(verificationId);
            showMessage({
              text: "Verification code has been sent to your phone.",
            });
          } catch (err) {
            showMessage({ text: `Error: ${err.message}`, color: "red" });
          }
        }}
      />
      <Text style={{ marginTop: 20 }}>Enter Verification code</Text>
      <TextInput
        style={{ marginVertical: 10, fontSize: 17 }}
        editable={!!verificationId}
        placeholder="123456"
        onChangeText={setVerificationCode}
      />
      <Button
        title="Confirm Verification Code"
        disabled={!verificationId}
        onPress={async () => {
          try {
            const credential = firebase.auth.PhoneAuthProvider.credential(
              verificationId,
              verificationCode
            );
            await firebase.auth().signInWithCredential(credential);
            showMessage({ text: "Phone authentication successful " });
          } catch (err) {
            showMessage({ text: `Error: ${err.message}`, color: "red" });
          }
        }}
      />
      {message ? (
        <TouchableOpacity
          style={[StyleSheet.absoluteFill, { backgroundColor: 0xffffffee, justifyContent: "center" }]}
          onPress={() => showMessage(undefined)}>
          <Text style={{color: message.color || "blue", fontSize: 17, textAlign: "center", margin: 20, }}>
            {message.text}
          </Text>
        </TouchableOpacity>
      ) : undefined}
    </View>
  );
}


text: Q: Difference between direct-list-initialization and copy-list-initialization? I know explicit constructor is not allowed for copy-list-initialization, but OK for direct-list-initialization.  Besides this, is there any other difference?


text:
Q: Brave Browser not showing ads I just started using Ubuntu 20.10 a few days ago.  I have been browsing with the Brave Browser
and have been very active.  Yet, I have not received a single ad yet.  Is anyone having this problem?  I have seen workarounds that involve deleting certain json files and restarting but this does not seem to work.
Update: Brave has an adblocker, but forwards its own ads to your notifications which you get paid for.


text:
Q: changing milliliters to liters with if statement hi for my assignment question which is
a method with the header public double getGuppyVolumeRequirement()
which returns the total number of litres required by all of the living
Guppies in the Pool. Note that the Guppy class has a helpful method
with returns the total number of milliLitres required per Guppy. You
will need to convert this to litres (note that 1,000 mL = 1 L).
in my guppy class i did the code for millilitres which is:
public double getVolumeNeeded() {
        if (getAgeInWeeks() < YOUNG_FISH) {
            return MINIMUM_WATER_VOLUME_ML;
        } else if (getAgeInWeeks() <= MATURE_FISH) {
            return MINIMUM_WATER_VOLUME_ML * getAgeInWeeks() / YOUNG_FISH;
        } else if (getAgeInWeeks() <= MAXIMUM_AGE_IN_WEEKS) {
            return MINIMUM_WATER_VOLUME_ML * 1.5;
        } else {
            return 0;
}

now im confused on how to make this to liters.
here is my return for guppies in pool
public int getPopulation() {
     return guppiesInPool.size();
}

A: Because 1L = 1000mL you can convert between liters to milliLiters and viceversa with the following formulas:
litres = milliLitres / 1000;

milliLitres = litres * 1000;

In your code you can replace instructions like:
  return MINIMUM_WATER_VOLUME_ML;    // Returns millilitres

With instructions like:
  return MINIMUM_WATER_VOLUME_ML / 1000;   // Returns litres

Or for most complicated formulas:
 // Returns millilitres
 return MINIMUM_WATER_VOLUME_ML * getAgeInWeeks() / YOUNG_FISH;

Change to
 // Returns litres
 return (MINIMUM_WATER_VOLUME_ML * getAgeInWeeks() / YOUNG_FISH) / 1000;

A: As you have a method which returns the millilitres required in your Guppy class, and 1L = 1000ml you may want to return
return liters = /* method which returns the total number of milliLitres required per Guppy */ / 1000;

if this getVolumeNeeded() method returns the millilitres you may want to have:
public double getVolumeNeeded() {
    if (getAgeInWeeks() < YOUNG_FISH) {
        return (MINIMUM_WATER_VOLUME_ML) / 1000;
    } else if (getAgeInWeeks() <= MATURE_FISH) {
        return (MINIMUM_WATER_VOLUME_ML * getAgeInWeeks() / YOUNG_FISH) / 1000;
    } else if (getAgeInWeeks() <= MAXIMUM_AGE_IN_WEEKS) {
        return (MINIMUM_WATER_VOLUME_ML * 1.5) / 1000;
    } else {
        return 0;
}

All you need to do is divide every return / 1000

A: since you already got ml required per guppy, just return volume required in liters as return MINIMUM_WATER_VOLUME_ML/1000.


text:
Q: difference between two time interval ios components swift 3 I have two time interval basically i want to convert find out difference between them this is my code. but, its not works
 func dateformatter(date:Double) -> String {

    let timeElapsed:TimeInterval = TimeInterval(Int(date))
    let timeNow:TimeInterval = TimeInterval(integerLiteral: Int64(Date().timeIntervalSince1970*1000))

    let date2:Date = Date(timeIntervalSince1970: timeElapsed )
    let date1:Date = Date(timeIntervalSince1970: timeNow )

    let calender:Calendar = Calendar.current
    let components:DateComponents = calender.dateComponents([.year, .month, .day, .hour, .minute], from: date1, to: date2)
    var returnString:String = ""
    print(components.second)
    if components.second! < 60 {
        returnString = "Just Now"
    }else if components.minute! >= 1{
        returnString = String(describing: components.minute) + " min ago"
    }else if components.hour! >= 1{
        returnString = String(describing: components.hour) + " hour ago"
    }else if components.day! >= 1{
        returnString = String(describing: components.day) + " days ago"
    }else if components.month! >= 1{
        returnString = String(describing: components.month)+" month ago"
    }else if components.year! >= 1 {
        returnString = String(describing: components.year)+" year ago"
    }
    return returnString
}

A: There is no need for all the conversion you doing at the beginning of the function. Date(timeIntervalSince1970:) accepts NSTimeInterval, however, it is only a typealias for double.
Also, because your first if statement check for seconds you need to include .seconds to the component parameter list.
Your could do the following:
func dateformatter(date: Double) -> String {

    let date1:Date = Date() // Same you did before with timeNow variable
    let date2: Date = Date(timeIntervalSince1970: date)

    let calender:Calendar = Calendar.current
    let components: DateComponents = calender.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date1, to: date2)
    print(components)
    var returnString:String = ""
    print(components.second)
    if components.second! < 60 {
        returnString = "Just Now"
    }else if components.minute! >= 1{
        returnString = String(describing: components.minute) + " min ago"
    }else if components.hour! >= 1{
        returnString = String(describing: components.hour) + " hour ago"
    }else if components.day! >= 1{
        returnString = String(describing: components.day) + " days ago"
    }else if components.month! >= 1{
        returnString = String(describing: components.month)+" month ago"
    }else if components.year! >= 1 {
        returnString = String(describing: components.year)+" year ago"
    }
    return returnString
}

A: Just a tip, there is an error in your logic which makes the function return "Just now" in every case. So here is the modified code:
func timeElapsed(date: Date) -> String {

        let date1:Date = date
        let date2: Date = Date() // Same you did before with timeNow variable

        let calender:Calendar = Calendar.current
        let components: DateComponents = calender.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date1, to: date2)
        print(components)
        var returnString:String = ""

        print(components.second!)

        if components.second! < 60 {
            returnString = "Just Now"
        }

        if components.minute! > 1{
            returnString = String(describing: components.minute!) + " mins ago"
        }
        else if components.minute! == 1 {

            returnString = "A minute ago"
        }

        if components.hour! > 1{
            returnString = String(describing: components.hour!) + " hours ago"
        }
        else if components.hour == 1 {

            returnString = "An hour ago"
        }

        if components.day! > 1{
            returnString = String(describing: components.day!) + " days ago"
        }
        else if components.day! == 1 {

            returnString = "Yesterday"
        }

        if components.month! > 1{
            returnString = String(describing: components.month!)+" months ago"
        }
        else if components.month! == 1 {

            returnString = "A month ago"
        }

        if components.year! > 1 {
            returnString = String(describing: components.year!)+" years ago"
        }
        else if components.year! == 1 {

            returnString = "A year ago"
        }

        return returnString
    }


text:
Q: How to remove/drop rows of nothing and NaN in Julia dataframe? I have a df which contains, nothing, NaN and missing. to remove rows which contains missing I can use dropmissing. Is there any methods to deal with NaN and nothing?
Sample df:
│ Row │ x       │ y    │
│     │ Union…? │ Char │
├─────┼─────────┼──────┤
│ 1   │ 1.0     │ 'a'  │
│ 2   │ missing │ 'b'  │
│ 3   │ 3.0     │ 'c'  │
│ 4   │         │ 'd'  │
│ 5   │ 5.0     │ 'e'  │
│ 6   │ NaN     │ 'f'  │

Expected output:
│ Row │ x   │ y    │
│     │ Any │ Char │
├─────┼─────┼──────┤
│ 1   │ 1.0 │ 'a'  │
│ 2   │ 3.0 │ 'c'  │
│ 3   │ 5.0 │ 'e'  │

What I have tried so far,
Based on my knowledge in Julia I tried this,
df.x = replace(df.x, NaN=>"something", missing=>"something", nothing=>"something")
print(df[df."x".!="something", :])

My code is working as I expected. I feel it's ineffective way of solving this issue.
Is there any separate method to deal with nothing and NaN?

A: You can do e.g. this:
julia> df = DataFrame(x=[1,missing,3,nothing,5,NaN], y='a':'f')
6×2 DataFrame
│ Row │ x       │ y    │
│     │ Union…? │ Char │
├─────┼─────────┼──────┤
│ 1   │ 1.0     │ 'a'  │
│ 2   │ missing │ 'b'  │
│ 3   │ 3.0     │ 'c'  │
│ 4   │         │ 'd'  │
│ 5   │ 5.0     │ 'e'  │
│ 6   │ NaN     │ 'f'  │

julia> filter(:x => x -> !any(f -> f(x), (ismissing, isnothing, isnan)), df)
3×2 DataFrame
│ Row │ x       │ y    │
│     │ Union…? │ Char │
├─────┼─────────┼──────┤
│ 1   │ 1.0     │ 'a'  │
│ 2   │ 3.0     │ 'c'  │
│ 3   │ 5.0     │ 'e'  │

Note that here the order of checks is important, as isnan should be last, because otherwise this check will fail for missing or nothing value.
You could also have written it more directly as:
julia> filter(:x => x -> !(ismissing(x) || isnothing(x) || isnan(x)), df)
3×2 DataFrame
│ Row │ x       │ y    │
│     │ Union…? │ Char │
├─────┼─────────┼──────┤
│ 1   │ 1.0     │ 'a'  │
│ 2   │ 3.0     │ 'c'  │
│ 3   │ 5.0     │ 'e'  │

but I felt that the example with any is more extensible (you can then store the list of predicates to check in a variable).
The reason why only a function for removing missing is provided in DataFrames.jl is that this is what is normally considered to be a valid but desirable to remove value in data science pipelines.
Normally in Julia when you see nothing or NaN you probably want to handle them in a different way than missing as they most likely signal there is some error in the data or in processing of data (as opposed to missing which signals that the data was just not collected).


text:
Q: How to set preferredTransform in AV Foundation video file copy I am using AVAssetReader and AVAssetWriter to transcode video from one file to another. AVAssetReaderTrackOutput was added to the AVAssetReader. Unfortunately, the single track's  preferredTransform property was not copied from the input to the output, so a video recorded in portrait orientation is played back in landscape.
How can I set the preferredTransform property in the output file?

A: I've just found my own answer: Set the transform property of the AVAssetWriterInput to the preferredTransform property of the input track, for example:-
assetWriterInput.transform = [[tracks objectAtIndex:0] preferredTransform];
Would have found this quicker in the doco if these two properties hadn't had different names for the same thing.


text:
Q: When does SQL SELECT statements throw exceptions? TSQL here. Specifically Server 2008(literally just upgraded)
Concerning stored procedures: Try/Catch
I was trying to make a list of cases when a Select Statement will throw an exception. The ones I can think of are syntax related(includes null variables) and divide by zero. I'm only guessing there are just a whole boat load of them for Insert/Alter and Create/Truncate.
If you happen to know of a good source link, that would be great.
This question came up when I was reading this exhaustive blog post about error handling for SQL server. It's titled for SQL Server 2000, but I think most of it still applies.
edit
Sorry, I meant to link this earlier. . .
http://msdn.microsoft.com/en-us/library/aa175920(v=sql.80).aspx

A: Outside for compile ("didnt' run") errors, you have at least these runtime errors

*

*arithmetic errors
These change based on various SET statement
Example: get sql server to warn about truncation / rounding

*overflow errors
example: one of the rows overflows smallint in some calculation

*CAST errors
eg you try ISNUMERIC in a WHERE or CASE and try to cast 'bob^' or 1.23 to int
See Why use Select Top 100 Percent?
However, you'd always want to use TRY/CATCH though, surely...?

A: Adding to gbn's post, you can also get locking errors like lock wait timeouts and deadlocks.
If you are referencing #Temp tables, you can get "Invalid object name '#Temp'" errors, because these are unbound until the statement executes.
If you are in READ UNCOMMITTED or WITH (NOLOCK), you can get error: 601 - "Could not continue scan with NOLOCK due to data movement."
If your code runs .NET code, you would probably get exceptions from there.
If your code selects from a remote server, you could a whole different set of errors about connections.


text:
Q: Excel VBA listobjects.add querytable error 9 I aim to get data from a csv file using an SQL request. I already made it successfully in a previous Workbook, so I copied it and modified it only on the SQL request part. I have an execution error 9 on the first line, which has not been modified after copying the code:
ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
    "ODBC;DBQ=" & Path & ";DefaultDir=" & Path & _
    ";Driver={Microsoft Access Text Driver (*.txt, *.csv)};DriverId=27;FIL=text", _
    ";MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;SafeTransactions=0;Threads=3;UID=admin;UserCommitSync=Yes;" _
    ), Destination:=ThisWorkbook.Sheets("Sessions").Range("$A$1")).QueryTable

The variable Path is the path to get to the folder where the file is stored. The Sheet "Sessions" is created before this line is ran, an is activated.
This is the complete code of the request:
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
    "ODBC;DBQ=" & Path & ";DefaultDir=" & Path & _
    ";Driver={Microsoft Access Text Driver (*.txt, *.csv)};DriverId=27;FIL=text", _
    ";MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;SafeTransactions=0;Threads=3;UID=admin;UserCommitSync=Yes;" _
    ), Destination:=ThisWorkbook.Sheets("Sessions").Range("$A$1")).QueryTable
    .CommandText = Array( _
    Selection & Chr(13) & Chr(10) & "FROM `" & NameFile(1) & "` `" & NameFile(2) & "`" & _
    Chr(13) & Chr(10) & Condition)
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .ListObject.DisplayName = "Session"
    .Refresh BackgroundQuery:=False
End With

I am quite new with connections in VBA, as it is only my second program using it. It is probably very simple to correct but I did not find a working solution for my case.

A: The problem is comming from the "Option base 1" and the array used by the recorder. Keeping the option and modifying the code to avoid array works, as well as well deleting the "Option Base 1".


text:
Q: How can a connected TCP socket send/receive multiple files simultaneously? Basically I got a listener that (when it receives a new connection) creates a new socketWorker and assigns the connection to the client to it.
Now if the client sends a huge file(that takes, say 30 seconds to be fully received) and afterwards sends a tiny file of a few bytes the tiny file isn't received until the huge file has been fully received.
This is obviously a bad approach and I wonder how I could do it so the files would be sent simultaneously?
As of now I'm using async methods, every time a file has been fully received BeginReceive() is called again to receive the next file (bad way).
Any way to fix this?
I'd appreciate it!

A: You'll have to implement multiplexing, like for example SPDY does. This is (basically) done by framing message parts and supplying a stream ID on each frame. This way, multiple streams can be exchanged over a single connection.
Alternatively, you could open one connection per file.


text:
Q: Al poner un div padre en FLEX, sus hijos pierden el width original Mi problema es que, tengo un div llamado articles que tiene de hijos a varios artículos, pero cuando le pongo display flex (para hacer un carousel con JavaScript), como que se achicharran y no encuentro la forma para que los artículos tengan su width (el que les puse en los styles.css). Había hecho un carousel antes, pero ahora me pasa esto.

Camisa Roja

$1500

3 cuotas sin interés

Envío gratis

Camisa Roja

$1500

3 cuotas sin interés

Envío gratis

Hay más articulos, pero es mucho codigo para poner acá. Le pongo display: flex al padre.
.articles {
    width: 100%;
    display: flex;
    flex-wrap: nowrap;
    /* grid-template-columns: repeat(1000, 23%);
    gap: 20px; */
    overflow: hidden;
    scroll-behavior: smooth;
    margin-bottom: 30px;
}

A los artículos, le puse width: 200px;
.article-product {
    width: 200px;
    /* width: var(--article-product-width); */
    margin: 15px 5px;
    padding-bottom: 20px;
    border: 1px solid rgba(149, 157, 165, 0.2);
    display: inline-block;
}

Sin embargo, cuando se juntan varios article-product, estos pierden el width que les había puesto, como lo puedo arreglar?


text:
Q: How to construct a railway tree and find the shortest way between two destinations? I'm trying to put a set of cities into a Python tree, but I haven't found the easiest method to do it.
I've built two trees that have one city in common.
Here are my trees:
As you see, Milan is the common city between both of them.
I tried to use this code:
class Foret:

    def __init__(self,item) :
        self.info = item
        self.child = None
        self.brother = None

    def getRootVal(self,) :
        return self.info

    def setRootVal(self,item) :
        self.info = item

    def getChild(self) :
       return self.child

    def getBrother(self):
       return self.brother

    def modifyChild(self,newNode):
       self.child = Foret(newNode)

    def modifyBrother(self,newNode):
       self.brother = Foret(newNode)

How can I transform the trees in the picture into Python trees?


text:
Q: Search a Column for Specified Text, Then Return the Sum of the adjacent column which contains values to sum I am creating a World Cup spreadsheet.
Example:
Team   | Pts |
Brazil | XXX |
Switz. | XXX |
C. Rica| XXX |
Serbia | XXX |
I have another table which displays the Country, Score & whether it was a W (win), L (loss) or T (tie). A WIN will add 3 points, a TIE will add 1 point & a LOSS will add 0 points. Where I put the XXX, I want a formula that will search the table column for the Country Name and ADD up the W's, L's & T's and display the sum of every game there team played with the point system I mentioned.
Any help would be greatly appreciated! Thanks.

A: Try,
=SUM(COUNTIFS(D:D, A2, E:E, {"T","W","W","W"}))

A: You can use COUNTIFS. I set up a mock table to demonstrate:
The first COUNTIFS will count a given teams wins, and then multiple by a factor of 3.
The second COUNTIFS will count a given teams ties (no need to multiply here).
Since a Loss equates to 0 points, there is no need to sum or count anything.
Adjust ranges to fit your setup and then auto-fill the equation down your table to calculate for each team.

A: You can use a formula in H2, as below, and drag down as many rows as required
=(3*SUMPRODUCT(--($A$2:$A$13=$G2),--($C$2:$C$13="W"))+SUMPRODUCT(--($A$2:$A$13=$G2),--($C$2:$C$13="T")))

Data:

You only care about Wins or Ties. So count the wins per country and * 3 and add to that the count of ties, which you don't need to multiply as is 1.
Sumproduct is used to handle the arrays nicely.


text:
Q: How to get all checkbox props with React + ASP.net mvc I am learning React and ASP.net( not core).
I try to create a small project for practice.
I have a number of checkboxes and a submit button.
The idea is when I click on the button I want to create a Jason that will contain a list of the checkboxes text and their states (check \uncheck).
That Jason I want to send to the server.
I mange to create the components and the relevant events.
But fail to create the following
1)  Get the state of the checkbox from the submit component and create a Jason out of it.
2)  Send that Jason to the server side (ASP.net).
I try to flow the tutorial but didn't get it, I tried to find solution on the internet but with no lack.
If someone can show me how to do it – or give me some direction that will help
Thanks
the jsk:
var data = [
  { Id: 1, ActionItem: "Action1" },
  { Id: 2, ActionItem: "Action2" },
  { Id: 3, ActionItem: "Action3" }
];
var Checkbox = React.createClass({
 getInitialState: function() {
   return {
    isChecked: false
   };
 },

 toggleChange: function() {
  this.setState({
   isChecked: !this.state.isChecked
   },
 function() {
   console.log(this.state);
  }.bind(this));
 },
 render: function() {
   return (

     <input type="checkbox"
     checked={this.state.isChecked}
     onChange={this.toggleChange} />{this.props.chkboxlabel}

  );
 }
});

var ActionBox = React.createClass({
  render: function() {
    return (

Select Action

        <CheckboxList data={this.props.data} />
        <SubmitForm/>

   );
  }
});

var CheckboxList = React.createClass({
  render: function() {
    var actionNodes = this.props.data.map(function(action) {
       return (
        <Checkbox chkboxlabel={action.ActionItem} key={action.id}>
          {action.ActionItem}
        </Checkbox>
    );
 });
 return (
    <form className="actionList">{actionNodes}
    </form>
   );
  }
});

var SubmitForm = React.createClass({
  handleSubmit: function(e) {
      //??
},
render: function() {
    return (
      <form className="actionForm" onSubmit={this.handleSubmit}>
        <input type="submit" value="Run" />
      </form>
    );
  }
});

ReactDOM.render(
   <ActionBox data={data} />,
   document.getElementById('content')
);

A: I found a solution that works I don't think it's the best way but maybe it will help other.
I loop thought the element to get the value- I believe there is a better way  of doing it with react.
var data = [
{ Label: "Action 1", IsChecked: false, Name: "a1" },
{ Label: "Action 2", IsChecked: false, Name: "a2" },
{ Label: "Action 3", IsChecked: false, Name: "a3" }

];
handleCommentSubmit: function () {
    var data = new FormData();
    var inputs = document.getElementsByName('mycheckbox');
    for (var i = 0; i < inputs.length; i++) {
        var name = inputs.item(i).value;
        var ischecked = inputs.item(i).checked;
        data.append(name, ischecked);
    }
    var xhr = new XMLHttpRequest();
    xhr.open('post', this.props.submitUrl, true);
    xhr.send(data);
},


text:
Q: Valums Ajax Uploader (Mutli) - Detect when all files are uploaded I am using the Valums Ajax Uploader to upload a batch of files. We recently changed the code from a single-upload a multi-upload type. This has raised a problem with our code.
As you can see, when the onComplete event fire, we reload the page to show newly uploaded images. However, the onComplete event seems to be firing after EACH file completes, and not after the entire batch does. This now causes a problem because when the first file finishes, the page reload attempt is fired and the uploader pops up an alert "If you leave this page, all heck will break loose on your remaining uploads" - or something to that effect.
I notice the onComplete event sends back a 0-based ID of the completed file, but I am not sure exactly how to use this to determine when the batch is done.
I guess my question is A) Is there a different event that triggers when all files are complete or B) How do I determine how many files the user has selected, in order to keep track in the onComplete event how many files have completed?
    var uploader = new qq.FileUploader({
        multiple: true,
        element: document.getElementById('file-uploader'),
        action: '/projectPhotoUpload.php',
        allowedExtensions: ['jpg', 'png', 'gif'],
        debug: true,
        params: {id: i},
        onComplete: function(id, fileName, responseJSON){
            window.location = 'projects.php?all=true&tab=1&sel=' + currProject;
        }
    })

A: Good answer, out of interest if you wanted to check the responseJSON to see if the files had uploaded, its set on the server script
return array('success'=>true, 'filename'=>$filename . '.' . $ext);

Then you can pick it up in the JS like
var success = responseJSON["success"]
var filename = responseJSON["filename"]

This way you could make a list of files and check the names on completion, or only decrement
if (success == true)

If the upload had failed, then you might not want it to decrement for example

A: You could add a counter that increments when an upload is started and decrements when complete.  Only redirect on complete when the counter is 0.
var running = 0;
var uploader = new qq.FileUploader({
    multiple: true,
    element: document.getElementById('file-uploader'),
    action: '/projectPhotoUpload.php',
    allowedExtensions: ['jpg', 'png', 'gif'],
    debug: true,
    params: {id: i},
    onSubmit: function(id, fileName){
        running++;
    },
    onComplete: function(id, fileName, responseJSON){
        running--;
        if(running==0){
          window.location = 'projects.php?all=true&tab=1&sel=' + currProject;
        }
    }
})

A: You'll need to add a cancel event in case the user cancels out of a file upload:
onCancel: function(id, fileName){running--;}

I'm debating the right approach to take here on my implementation. I also would like to have the page redirect once the files are uploaded but what if the user intends to upload more files; the files may be spread out in separate directories.
Seems like the best approach is to have an "I'm Done" button that will redirect once the user is finished uploading.

A: A simpler way would be to use the inner property _filesInProgress to check if all uploaded files have been treated.
It would give:
var uploader = new qq.FileUploader({
    multiple: true,
    element: document.getElementById('file-uploader'),
    action: '/projectPhotoUpload.php',
    allowedExtensions: ['jpg', 'png', 'gif'],
    debug: true,
    params: {id: i},
    onComplete: function(id, fileName, responseJSON){
        if(uploader._filesInProgress == 0){
            window.location = 'projects.php?all=true&tab=1&sel=' + currProject;
        }
    }
});


text:
Q: any one can explain the Registration Service working at server in iOS for my website         NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"www.bikrionline.com/database/iqry_mbr_mst.php"]];
        // create the Method "GET" or "POST"

        [request setHTTPMethod:@"POST"];

        //Pass The String to server
    NSString *userUpdate =[NSString stringWithFormat: @"txtemail=%@&txtpwd=%@&txtcpwd=%@", email, password,confirmpassword];

        //Check The Value what we passed
        NSLog(@"the data Details is =%@", userUpdate);

        //Convert the String to Data
        NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];

        //Apply the data to the body
        [request setHTTPBody:data1];

        //Create the response and Error

        NSError *err;
        NSURLResponse *response;

        NSData *responseData = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&err];

        NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

        //This is for Response
        NSLog(@"got response==%@", resSrt);

        if(resSrt)
        {
//            NSLog(@"got response");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Registration" message:@"Congratulations you account has been created successfully" delegate:self cancelButtonTitle:@"Delete" otherButtonTitles:nil, nil];
            [alert show];

        }
        else
        {
            NSLog(@"faield to connect");
        }

}

A: it may not be working because the URL you have given without HTTP try changing your code like this
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.bikrionline.com/database/iqry_mbr_mst.php"]];


text:
Q: RDLC report not working on server but working on local machine RDLC report working fine on local system but when running on the server getting error

The element 'buildProviders' cannot be defined below the application
  level.

I added the Microsoft Report Viewer 2012 Runtime but still getting the same error. I am using .Net framework 4


text:
Q: enzyme mount fails when there is a function call in the componentDidMount I have a react component and in there I have a click function as follows:
    clickTwitter(e) {

    e.stopPropagation();
    let storyId = this.refs.storyToTweet.getAttribute('id');
    if (storyId != undefined) {
        let storyIdValue = this.props.storyId;
        this.postOnTwitter(storyIdValue);
    }
}

and in componentDidMount I have the following:
    componentDidMount(){
    this.fbInit();
}

fbInit(){
    return facebookInitializer= function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = `https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.12&appId=${FACEBOOK.appId}&autoLogAppEvents=1`;
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk');

}

I have the following test case:
        it('should call the clickTwitter method once', () => {
        // creates the spy for the clickTwitter method
        let clickTwitterSpy = sinon.spy(StoryMedia.prototype, 'clickTwitter');
        let props={

        }
        // wraps the component by using the enzyme mount method
        const wrapper = mount(<StoryMedia/>);

        // simulates a user clicking the twitter button
        wrapper.find('.shareTwitterDummy').simulate('click');
        // asserts that the clickTwitter method was called once when the button was clicked
        assert.strictEqual(StoryMedia.prototype.clickTwitter.calledOnce, true);
        // restores the method to its original state
        clickTwitterSpy.restore();
    });

when I run the test I get the following strange error:
TypeError: Cannot read property 'parentNode' of undefined....

If I remove the this.fbInit(); from componentDidMount everything works.
Is there anyway I can tell the test to ignore the this.fbInit()? Or any other solution is appreciated

A: I think that var js, fjs = d.getElementsByTagName(s)[0]; fjs is undefined


text:
Q: Error: Failed to activate control 'VB.userControl'. This control may be incompatible with your application I was getting the error:

"Failed to activate control 'VB.userControl'. This control may be
  incompatible with your application. Make sure you are using the
  version of the control that was provided with your application. after
  installing two applications."

I noticed that after I first installed one application, it was working fine. I can launch the first program and use it.
However after I installed the second application and restart then launch the second program. It gives me the error on the first program upon launching it.
I tried to uninstall and reinstall the first application and launch it again, it will work but the second application will now get the error.
I saw another answered question with the same error here however I think mine is quite different as I am dealing with two applications.
Thanks in advance. :)

A: Welcome to what used to called "DLL hell".  You have two applications installing two versions of the same DLL (or OCX, same thing).  If you know which .dll or .ocx file is the source of the problem, you can use one of several DLL or COM redirect techniques.  I have used the ".local" approach to force a VB6 application to load a specific version of an OCX:
https://learn.microsoft.com/en-us/windows/desktop/dlls/dynamic-link-library-redirection
Good luck!


text:
Q: How to deal with random pop up window in puppeteer js I have a pop up window that appears on the page randomly.  Usually about 20 seconds after I go on a page.

        <form novalidate="novalidate" class="bluecoreEmailCaptureForm" id="bluecoreEmailCaptureForm" name="bluecoreEmailCaptureForm">

<<<< OTHER HTML >>>>

        </form>

Is the best way to deal with this just to wait for the selector to appear and then click it off?
Or would is there another way to deal with dialogues (popups).
await page.waitForSelector('.bluecoreActionScreen');

Then click it off?

A: You can use waitForSelector like this:
await page.waitForSelector('.bluecoreActionScreen')

and then remove the element by CSS or DOM after that:
await page.evaluate(() => {
    let popupElement = document.querySelector('.bluecoreActionScreen')
    // BY CSS DISPLAY NONE
    popupElement.style.display = 'none'
    // OR BY REMOVE THE ELEMENT DOM
    popupElement.parentElement.removeChild(popupElement)
})


text:
Q: How to create dynamic sql string according to unknown column count I think the title is clearly. There is a sqlite app in android. The app is when starts, it's creates a database and tables. But the tables, columns, types, column count absolutely not specific. So, I need to create a perfect dynamic structure. I will take columns, tables, types and anything of about database from a xml. That is the point, the xml...
String query = "CREATE TABLE IF NOT EXISTS a(" + col_parameter1 +" " type_paramater1+","+ ... col_paramaterN + " " + type_parameterN +")" ;

I dont know how many creates table, how many colunms. I do try too way but all of them not perfect.

A: Try this. I think it will help you
class Column {
    String name;
    String type;
}

public class Main{

//Fill colums with data read from xml

 public String createTableQuery(List<Column> colums){
        StringBuffer  query = new StringBuffer();
        query.append("CREATE TABLE IF NOT EXISTS a(") ;
        for(int i = 0; i < colums.size(); i++){
            Column col = colums.get(i);
            query.append(" " + col.name + " " +col.type + ", ");
        }
        query.append(")");

        return query.toString();
 }

}


text:
Q: Pulling Images into RSS feed using Salesforce Marking Cloud Email I am trying to pull images into my email from our RSS feed (after installing the 'Send Images to RSS' wordpress plug in) but I keep getting this error:
Invalid index (parameter 2) passed to Row function. Index must be less than or equal to the row count.
Index Value: 1
Row Count: 0
Function: Row(@images,@cnt)

I have no idea how to fix this.
Here is the important part:
%%[Var @xml, @titles, @title, @descs, @desc, @links, @link, @cnt, @images, @image
Set @xml = HTTPGet("http://hotelmanager-blog.trivago.com/feed/email")
Set @titles = BuildRowsetFromXML(@xml,"//item/title",1)
Set @descs = BuildRowsetFromXML(@xml,"//item/description",1)
Set @links = BuildRowsetFromXML(@xml,"//item/link",1)
Set @images = BuildRowsetFromXML(@xml,"//item/img",1)

If RowCount(@titles) > 5 THEN
SET @rows = 5
ELSE
SET @rows = RowCount(@titles)
ENDIF

IF @rows >= 1 THEN
for @cnt = 1 to @rows do
Set @title = Field(Row(@titles,@cnt),"Value")
Set @link = Field(Row(@links,@cnt), "Value")
Set @desc = Field(Row(@descs,@cnt), "Value")
Set @image = Field(Row(@images,@cnt), "url_att")

]%%

A: Your XPATH of //item/img is expecting there to be an img node -- on the same level as title and description.  Since it doesn't exist in your XML, it can't retrieve it.   That's why you're getting an error.
You can code it more defensively by checking the rowcount() for every node could be missing.
Here's what I typically do (updated your your feed):
%%[

set @xml = httpget("http://hotelmanager-blog.trivago.com/feed/email")

var @i, @maxToDisplay, @nodes, @rowCount

set @nodes = BuildRowsetFromXML(@xml,"//item/*",0)
set @rowCount = rowcount(@nodes)

set @maxToDisplay = 5

set @rowCount = iif(@rowCount > @maxToDisplay, @maxToDisplay, @rowCount)

if @rowCount > 0 then

  for @i = 1 to @rowCount do

    var @title
    var @pubDate
    var @categoryNodes
    var @categories
    var @link
    var @image

    set @title = Field(Row(BuildRowsetFromXML(@xml,concat("//item[",@i,"]/title"),0),1),'Value')
    set @pubDate = Field(Row(BuildRowsetFromXML(@xml,concat("//item[",@i,"]/pubDate"),0),1),'Value')
    set @link = Field(Row(BuildRowsetFromXML(@xml,concat("//item[",@i,"]/link"),0),1),'Value')

    if rowcount(BuildRowsetFromXML(@xml,concat("//item[",@i,"]/image"),0)) > 0 then
      set @image = Field(Row(BuildRowsetFromXML(@xml,concat("//item[",@i,"]/image"),0),1),'Value')
    endif

    set @categoryNodes = BuildRowsetFromXML(@xml,concat("//item[",@i,"]/category"),0)
    set @categories = rowcount(@categoryNodes)

    if not empty(@title) then

         outputline(concat("

Title: ", @title))
         outputline(concat("
PubDate: ", FormatDate(@pubDate, "MMM DD, YYYY hh:MM tt")))
         outputline(concat("
link: ", @link))
         outputline(concat("
image: ", @image))
         outputline(concat("
categories: ", @categories))

         var @j
         var @category

         for @j = 1 to @categories do

          set @category = Field(row(BuildRowsetFromXML(@xml,concat("//item[",@i,"]/category[",@j,"]"),0),1),"Value")
          outputline(concat("
category ", @j ,": ", @category))

         next @j

    endif

  next @i

else

  raiseerror("no articles found")

endif

]%%

Output
Title: The Future of Luxury Travel & Hospitality at ITB Berlin
PubDate: Mar 10, 2017 03:03 PM
link: http://hotelmanager-blog.trivago.com/future-luxury-travel-hospitality/
image:
categories: 2
category 1: Discover Industry Highlights
category 2: Feature

Title: Metasearch Helps Hoteliers Drive Direct Bookings
PubDate: Mar 10, 2017 02:03 AM
link: http://hotelmanager-blog.trivago.com/metasearch-helps-hoteliers-drive-direct-bookings/
image:
categories: 6
category 1: Discover Industry Highlights
category 2: Uncategorized
category 3: Events & Webinar
category 4: Feature
category 5: Hotel Metasearch Marketing Tips
category 6: Hotel technology

Title: The Future of Travel Comes to Life at ITB Berlin 2017
PubDate: Mar 08, 2017 12:03 PM
link: http://hotelmanager-blog.trivago.com/future-of-travel-itb-berlin-2017/
image:
categories: 6
category 1: Discover Industry Highlights
category 2: Events & Webinar
category 3: Feature
category 4: Hotel Metasearch Marketing Tips
category 5: Hotel technology
category 6: Industry Trends

Title: trivago Hotel Manager makes Scotland debut at ScotHot 2017
PubDate: Mar 03, 2017 07:03 AM
link: http://hotelmanager-blog.trivago.com/trivago-hotel-manager-scotland-debut-scothot-2017/
image:
categories: 4
category 1: Discover Industry Highlights
category 2: Direct Bookings
category 3: Events & Webinar
category 4: Hotel technology

Title: Let's Meet at the World's Leading Travel Tradeshow – ITB Berlin
PubDate: Mar 02, 2017 10:03 AM
link: http://hotelmanager-blog.trivago.com/lets-meet-worlds-leading-travel-tradeshow-itb-berlin/
image:
categories: 2
category 1: Videos
category 2: Events & Webinar


text:
Q: similar values highlight in same row Excel vba I have an Excel sheet data from B2: AF7. (data in 6 rows and 31 columns)
my need is...
if user input three values, then same row similar values from columns B2:AF7 should be highlight with color
values starts from B column.
values like these
sheet 1:
B column
1919106
1825168
1856294
2038838
1891278
1799495
till column AF7

any solutions ...

A: For this question i use Sheet1 and yellow background.
Try:
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim ImportValue As String
    Dim i As Long
    Dim RowNo As Long
    If Not Intersect(Target, Range("$B$2:$AF$7")) Is Nothing Then

        RowNo = Target.Row
        ImportValue = Target.Value

        For i = 2 To 32
          If ImportValue <> "" And ImportValue = Sheet1.Cells(RowNo, i).Value Then
            With Target.Interior
                .Color = 65535
            End With
            With Sheet1.Cells(RowNo, i).Interior
                .Color = 65535
            End With
          End If
        Next i

    End If

End Sub


text:
Q: Show that $R = \{ (x,y) \in \mathbb{Z} \times \mathbb{Z} : 4 \mid(5x+3y)\}$ is an equivalence relation.
Let $R$ be a relation on $\mathbb{Z}$ defined by $$ R = \{ (x,y) \in \mathbb{Z} \times \mathbb{Z}  :  4 \mid (5x+3y)\}.$$ Show that $R$ is an equivalence relation.

I'm having a bit of trouble with this exercise in my book and I am trying to study. Can anyone give guidance for this? I know we have to show reflexivity, symmetry, and transitivity, but I don't think what I have on my paper is completely right. I would appreciate other people's opinions on what the solution should be.

A: This should be easily verified if we realize that
$$4|(5x+3y) \quad \Longleftrightarrow \quad 5x+3y \equiv 0 \pmod 4 \quad \Longleftrightarrow \quad x \equiv y \pmod 4.$$

A: Reflexive: $xRx = 5x + 3x = 8x$ which is clearly divisible by $4$ if $x\in\mathbb Z.$
Symmetry: Assume $xRy$, that implies that $5x + 3y$ is divisible by $4$.
Then $yRx = 5y + 3x = (9y - 4y) + (15x - 12x) = 9y + 15x - 4y - 12x $$= (3y + 5x)- 4(y + 3x).$  Since $3y + 5x$ is divisible by $4$ and $4(y + 3x)$ is divisible by $4$, their difference is divisible by $4$ too, when $x$ and $y$ are integers.
Transitivity: Assume $xRy = 5x + 3y$ and $yRz = 5y + 3z$. Sum them together and you get the $5x + 8y + 3z$, which is divisible by $4$ (since you added two terms divisible by $4$), so $5x + 8y + 3z - 8y$ must also be  divisible by $4$ (because you subtracted a number divisible by $4$ from an expression divisible by $4$) and there you get the $xRz$.

A: In general, let $a$ and $b$ be integers and $m$ a positive integer.  Then, $$R:=\big\{(x,y)\in\mathbb{Z}\times\mathbb{Z}\,|\,ax+by\text{ is divisible by }m\big\}$$ is an equivalence relation on $\mathbb{Z}$ if and only if $m$ divides $a+b$.  Furthermore, if $m$ divides $a+b$, then the set of equivalence classes of $\mathbb{Z}$ under $R$ is precisely $\mathbb{Z}/R = \mathbb{Z}/d\mathbb{Z}$ (i.e., $R$ is exactly congruence modulo $d$), where $d:=\frac{m}{\gcd(m,a)}=\frac{m}{\gcd(m,b)}$.

A: Though the other  answers give a good impression of why $x\sim y\iff 4|(5x+3y)$ defines an equivalence relation, it needs to be said that this is not exactly what is asked in the OP. The OP literally asks:

Show that $R = \{ (x,y) \in \mathbb{Z} \times \mathbb{Z}  :  4 | (5x+3y)\}$ is an equivalence relation.

Then one should say: $R$ is not an equivalence relation. $R$ is a set. More precisely, $R$ is a subset of the set $\mathbb Z\times \mathbb Z$. Its definition relies heavily on the equivalence relation mentioned in the first line of this answer, but it is not itself an (equivalence) relation.
This might seem pedantic, but absolute unambiguous clarity is everything to  a mathematician.


text:
Q: Should 'is' be added? "With the utilization of very few resources, the problem is solved aptly and is demonstrated by simulation results"
I doubt if 'is' should be written or not.

A: Repeating the 'is' is optional, but, for me, it is better not to repeat the same word twice, because not only will it be better aesthetically, but also it will sound better when you hear it.
So, you should write "With the utilization of very few resources, the problem is solved aptly and demonstrated by simulation results"

A: In this case, you might want repeat the is. This keeps the sentence from being ambiguous.
If you just say

the problem is solved aptly and demonstrated by simulation results

the reader can't tell whether the problem was solved aptly by the simulation results, or whether it the simulation results just demonstrated the solution.
If you say

the problem is solved aptly and is demonstrated by simulation results,

the second is makes it clearer that the phrase by simulation results only applies to the verb demonstrated.
Actually, there is no reason to try to avoid grammatical ambiguity when only one of the possibilities makes sense, so there is no actual ambiguity. Everybody says

... was buried and eaten by worms,

and not

... was buried and was eaten by worms,

because it's quite clear that worms don't bury people. I suspect this if you know the subject matter, your sentence isn't actually ambiguous, so there's nothing wrong with leaving out the is.


text:
Q: Cannot get PyCharm Django project to read and display Django Templating Language Tags I have been pulling my hair out over this, am new to using Django for web development and I have never setup a Django project in PyCharm. It is Django v2.0 and PyCharm 2017.3.
I have a basic project which consists of two apps, for examples sake lets call one Test and one TestProj. Test is the core of the site where settings.py is located, and TestProj is where I wish to add templates.
The Test urls.py points to the TestProj urls.py, which when requested, serves a html file to the root url of the site. This content is located in a folder again called Test which is located in a templates folder in TestProj
Essentially the directory structure is as follows:
Test  >
    settings.py etc
TestProj  >
    templates  >
        Test  >
            index.html
            header.html
    other python files are here!

The index.html file is served fine but the problem occurs when I try to use Django templating to link in another html file. This is index.html:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Test</title>

           {% block content %}
           {% endblock %}

And this is header html which is located in the same templates directory:
{% extends 'Test/index.html' %}

{% block content %}

Hello World

{% endblock %}

index.html is served as normal but for some reason no matter what I do the
Django {% block content %} in index.html doesnt seem to evaluate. Thus, my index.html, when served in the browser with Pycharm, has an empty body instead of Hello World.
The Test folder within templates is marked as a template folder in PyCharm so I don't see why this is the case. I also have Django selected as the template language in PyCharm settings and I have tried reinstalling PyCharm. The settings.py templates is also correctly configured to my knowledge as below:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'TestProj/templates/Test')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Any help would be very much appreciated!

A: make sure that you set  "Project Interpreter" correctly:
https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html

A: I've fixed this, turns out it was stupidity in my views.
I was linking to index.html when rendering instead of header, which is supposedly how extends works.


text:
Q: add XML support to JSON handling functions in ROR In my heroku RoR app,I have a controller in which I support JSON requests. There I have the following functions:
def mssg_as_json
    @message = Message.new
    @message.text = params.require(:messages)
    @message.save
    string = "http://link.com/"
    @message.url = string + @message.id.to_s
    @message.save
    render json: { url: @message[:url] }
end

def return_mssg_as_json
  if @message = Message.find_by(id: params[:id])
    render json: { message: @message[:text] }
  else
    render json: {errors: :not_found}, status: :not_found
  end
end

I want to support XML requests too. My idea is to somehow convert the XML to JSON but I have no idea how. How can I modify the code to support both XML and JSON?
P.S.
My routes are:
get "messages/api" => "messages#return_mssg_as_json"
post "messages/api" => "messages#mssg_as_json"

The requests are send to main_url/messages/api

A: So, you should take advantage of the standard routes and actions. In routes.rb, you might do something like:
Rails.application.routes.draw do
  resources :messages
  namespace :api, defaults: {format: 'json'} do
    namespace :v1 do
      resources :messages
    end
  end
end

Note that your controller is now nested inside api/v1. That allows you to identify the path as an api and to maintain versions over time. That solid's practice. Also note that you have a standard messages resource for your web app.
Then, your controller would look like:
class Api::V1::MessagesController < Api::V1::BaseController

  def create
    @message = Message.new(message_params)
    respond_to do |format|
      if @message.save
        @message.update(url: "http://link.com/#{@message.id}")
        format.json { render json: create_hsh, status: :ok }
        format.xml  { render xml: create_hsh, staus: :ok }
      else
        format.json { render json: @message.errors, status: :unprocessable_entity }
        format.xml  { render xml:  @message.errors, status: :unprocessable_entity }
      end
    end
  end

  def show
    respond_to do |format|
      if @message = Message.find_by(id: params[:id])
        format.json { render json: show_hsh, status: :ok }
        format.xml  { render xml: show_hsh, status: :ok }
      else
        format.json { render json: {errors: :not_found}, status: :not_found }
        format.xml  { render xml: {errors: :not_found}, status: :not_found }
      end
    end
  end

private

  def create_hsh
    @message.attributes.with_indifferent_access.slice(:url)
  end

  def show_hsh
    attr = @message.attributes.with_indifferent_access
    attr.slice(:foo, :bar).merge!(message: attr[:text])
  end

  def message_params
    params.require(:message).permit(:text)
  end

end

Note that this controller inherits from Api::V1::BaseController. That would be a controller that you set up to do api-relevant client authentication (key/token checking, etc.). Something, perhaps, like:
class Api::V1::BaseController < ActionController::API
  before_action :authorize

  def authorize
    # do your checks in a way that results in a variable @authorized?
    render(json: {errors: :unauthorized}, status: :unauthorized) unless @authorized?
  end

end

So, now you're using a single controller action to respond to all format types (that you elect to offer). Then, you clients would post something like:
http://your.api.com/messages.json

To get a json response. Or:
http://your.api.com/messages.xml

To get an xml response. You might notice the bit that says: namespace :api, defaults: {format: 'json'} do. This means that your client could call:
http://your.api.com/messages

and it will default to the json format.
Now you don't have a bunch of random endpoints (like mssg_as_json), just the regular RESTful ones that your clients will expect. Your API clients will love you for that.
You'll note that show_hsh is the accepted code from your earlier question.


text:
Q: showing UTF-16 emojis received from JSON in text view - Android I got the emoji as UTF 16 in JSON and the json look like this
{
   "name":"Crying Face"
  ,"code":"\\ud83d\\ude22"
}

I tried to write the code in textview but it is printed as text
I tried also to convert the \u to 0x
0xd83d0xde22

It prints it out as plain text
how can we show it as Emoji?
UPDATE:
after i saved the object to database the \\ was removed and it looks like this in the database:

A: Why is it \\u?   It should be \u.  \u escapes the \, making it a literal \ so the emoji isn't recognized as a character escape code.

A: Try using EmojiconTextView of this custom library: https://github.com/rockerhieu/emojicon
android:text="I \ue32d emojicon"

In this way, you can set any emoji like you do for any string.


text:
Q: Como mostrar fecha en formato yyyy/mm/dd en Javascript Estoy creando un sistema web y colocando una fecha actual en forma de widget que se muestre cada vez que se ejecute la ventana lo he hecho en javascript si funciona me muestra de la siguiente manera 6/2/2021, lo que quiero es agregarle los ceros quedando de esta forma 06/02/2021.
Este es el código:
    function fecha_atual() {

var fecha = new Date();

  var mes = fecha.getUTCMonth() + 1;

  var dia = fecha.getUTCDate();

  var año = fecha.getUTCFullYear();

  document.getElementById("fecha").innerHTML = dia + "/" + mes + "/" + año;

}

fecha_atual();

setInterval(fecha_atual, 1000);

A: Puedes agregar el cero con un operador condicional así:
var mes = (fecha.getUTCMonth()<=10?'0':'')+(fecha.getUTCMonth()+1);
var dia = (fecha.getUTCDate()<10?'0':'')+fecha.getUTCDate();


text:
Q: Why are collision checks in Unity2D providing various outcomes? I'm trying to recreate AA in Unity2D to kind of learn how everything works, I'm using a YouTube tutorial to guide me through it and I have the exact code in the video but it doesn't seem to be working correctly, the pins won't stop at the same time when they touch the rotating ball (seen below). Some will go halfway into the ball while others will stop prematurely.

Here's the pin code (Pin.cs):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pin : MonoBehaviour {

    private bool moving = true;

    public float speed = 20f;
    public Rigidbody2D rb;

    void Update() {
        if (moving)
            rb.MovePosition(rb.position + Vector2.up * speed * Time.deltaTime);
    }

    void OnTriggerEnter2D(Collider2D collider) {
        if (collider.tag == "Rotator") {
            moving = false;
            transform.SetParent(collider.transform);
        }
    }
}

A: Just use FixedUpdate() instead Update().
Refer to Unity Documentation - FixedUpdate link, FixedUpdate() should be used instead of Update() when dealing with Rigidbody.
So, Change your code to this:
public class Pin : MonoBehaviour
{
    ...

    void FixedUpdate()
    {
        if (moving)
            rb.MovePosition(rb.position + Vector2.up * speed * Time.deltaTime);
    }

    void OnTriggerEnter2D(Collider2D collider)
    {
        ...
    }
}

I hope it helps you.


text:
Q: Memory Mapped Files and Max File Size I am using boost::iostreams::mapped_file_source to create a memory mapped files. In excess of 1024. To my surprise when I have created around 1024 memory mapped files my program throws an exception stating there are too many files open. After some research I found that Ubuntu uses a max file size per processes of 1024 (found from ulimit -n). Unfortunately, I need all of the files to be open at the same time. Does anyone know a way around this? Is it possible to make the files not count towards the limit someway? I was thinking of trying to combine them into a single file; however, I would like to avoid that if possible due to the performance. And I would also like to not modify the operating system by changing the value. Any points in the correct direction are much appreciated!

A: Why do you need many mapped files open? That seems very inefficient. Maybe you can map (regions of) a single large file?

Q.  I was thinking of trying to combine them into a single file; however, I would like to avoid that if possible due to the performance

That's ... nonsense. The performance could basically only increase.
One particular thing to keep in mind is to align the different regions inside your "big mapped file" to multiple of your memory page/disk block size. 4k should be a nice starter for this coarse alignment.


text:
Q: Stored Procedure using where with multiple if else and different table ALTER PROCEDURE [dbo].[SP_Something]
(
    @Search_Text VARCHAR(4000),
    @FILTER INT
)
AS
BEGIN
    SELECT  Customer_Information
    FROM    Customer
    LEFT OUTER JOIN Something K
            ON  K.Something _Id= Something_Id2
    LEFT OUTER JOIN  Something3 KS
            ON KS.Something_Id =Something_Id3
    WHERE
        (Filter = 1 AND Customer_İnformation LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 2 AND Customer_name LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 3 AND Customer_Adress LIKE '%' + @Search_Text + '%')
END

I get all datas from Customer Table.
I need to get data from PRODUCT_TABLE for my below code,
(Filter = 3 AND Customer_Adress LIKE '%' + @Search_Text + '%')
from PRODUCT_TABLE

how can i achieve this inside "where" in Ms Sql?
Any help will be appreciated.
Thanks.

A: ALTER PROCEDURE [dbo].[SP_Something]
(
    @Search_Text VARCHAR(4000),
    @FILTER INT
)
AS
BEGIN
    IF Filter IN (1,2)
    SELECT  Customer_Information
    FROM    Customer
    LEFT OUTER JOIN Something K
            ON  K.Something _Id= Something_Id2
    LEFT OUTER JOIN  Something3 KS
            ON KS.Something_Id =Something_Id3
    WHERE
        (Filter = 1 AND Customer_İnformation LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 2 AND Customer_name LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 3 AND Customer_Adress LIKE '%' + @Search_Text + '%')

    IF Filter = 3
    SELECT  YourField
    FROM    ProductTable
    WHERE
        (Filter = 3 AND YourSearchField LIKE '%' + @Search_Text + '%')

END

A: ALTER PROCEDURE [dbo].[SP_Something]
(
    @Search_Text VARCHAR(4000),
    @FILTER INT
)
AS
BEGIN
    SELECT  Customer_Information
    FROM    Customer
    LEFT OUTER JOIN Something K
            ON  K.Something _Id= Something_Id2
    LEFT OUTER JOIN  Something3 KS
            ON KS.Something_Id =Something_Id3
    LEFT OUTER JOIN  PRODUCT_TABLE P
            ON P.Something_Id = KS.Something_Id3

    WHERE
        (Filter = 1 AND Customer_İnformation LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 2 AND Customer_name LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 3 AND Customer_Adress LIKE '%' + @Search_Text + '%')
        OR
        (P.Filter = 3 AND P.Customer_Adress LIKE '%' + @Search_Text + '%')

END

I think another thing you are missing here is, in your Where clause you havent mentioned anything about which Filter is from which table, Use the table alias before the column names like I have it makes code easier to read and easier to maintain and resolves column ambiguity .


text:
Q: PHP and Apache configuration in uploading data to database I encountered problem in my configuration of my php because not all data was uploaded to database eventhougn my files is not large it was only KB.
my server is apache.
I already edit this:
•max_input_time

•memory_limit

•max_execution_time

•post_max_size

but still not all data was save to my database..
I tried everything and yet, nothing was change. still not all was save to my database
Thank you


text:
Q: Load large json file from external website with D3 On my site "mywebsite.com" I have a D3 javascript code running on some data set located at "otherwebsite.com/data.json", so I naively tried
d3.json("otherwebsite.com/data.json", function(error, json) {
if (!error) {

    console.log('done loading',json)
} else {
    console.log(error)
}
})

but of course it does not work :)
Access to XMLHttpRequest at 'otherwebsite/data.json' from origin 'https://mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Anyone has a better idea? I should emphasize that it is a large file (200MB).
Thanks

A: Taken from the MDN page on CORS:

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.

The CORS header in question is Access-Control-Allow-Origin which needs to either be explicitly set to https://mywebsite.com or be set to something that includes that, such as *.
If you have access to the server for "otherwebsite.com" you can change the header being sent with the request.
Otherwise you'll probably have to download the data server side on "mywebsite.com" and then have the front end request it from your back end, rather than making a cross origin request, so you'll change the JS to look like:
d3.json("/data.json", function(error, json) {...


text:
Q: Windows forms calculator algorithms. Sorting and highest/lowest numbers I'm currently working on a calculator but 2 of my algorithms are not working correctly.

*

*In my history (listbox) I get the numbers from the calculator and I have a bottom that finds the smallest number. I get an error with my code.

*I want to have a [sorting] bottom that sorts the numbers ascending or descending. I've tried things as listbox1.sorted but I only get it to work as alphabetic.
If you know what I'm doing wrong with nr.1 or know how to fix a sorting algorithm please let me know.
 int count = 0;
 int tal = 0;
 double Mtal = 999999999999999999;
 bool hit;
 int count1 = 0;
 private void button26_Click(object sender, EventArgs e)
    {
        while (count < 100)
        {
            foreach (var Listboxitem in listBox1.Items)
            {
                hit = false;
                if (Convert.ToDouble(Listboxitem) < Mtal)
                {

                    Mtal = Convert.ToDouble(Listboxitem);
                    hit = true;
                }
                count = count + 1;
                if (hit)
                {
                    count1 = count;
                }
            }
        }
        this.listBox1.SelectedIndex = count1 - 1;

    }

A: Your values in ListBox are Integers. So change the declaration of your variable Mtal from double to int. And then, instead of Convert.ToDouble() use int.Parse(), because you need integers for comparing to existing min value.
Something like this should work for you:
 int count = 0;
 int tal = 0;
 int Mtal = int.MaxValue;
 bool hit;
 int count1 = 0;
 private void button26_Click(object sender, EventArgs e)
 {
     while (count < 100)
     {
          foreach (var Listboxitem in listBox1.Items)
          {
             hit = false;
             if (int.Parse(Listboxitem.ToString()) < Mtal)
             {

                 Mtal = int.Parse(Listboxitem.ToString());
                 hit = true;
             }
             count = count + 1;
             if (hit)
             {
                count1 = count;
             }
        }
    }
    this.listBox1.SelectedIndex = count1 - 1;

 }

And then for Ordering I would suggest you to use LINQ on List<ListItem>. For your example:
private void button_OrderByDescencing_Click(object sender, EventArgs e)
 {
        List<ListItem> items= new List<ListItem>();
        foreach (ListItem a in lb.Items)
        {
            items.Add(a);
        }
        items=items.OrderByDescending(a => int.Parse(a.Value)).ToList();
        foreach (ListItem a in items)
        {
             listBox1.Items.Add(a);
        }

 }

And for ascending:
 private void button_OrderByAscending_Click(object sender, EventArgs e)
 {
        List<ListItem> items= new List<ListItem>();
        foreach (ListItem a in lb.Items)
        {
            items.Add(a);
        }
        items= items.OrderBy(a => int.Parse(a.Value)).ToList();
        foreach (ListItem a in items)
        {
             listBox1.Items.Add(a);
        }

 }


text:
Q: Visual studio desginer view is zoomed, how can i get the actual size? Image Problem: form designer bigger then actual size.
Maybe this is a stupid question but I havn't found any solution. So my designer view is zoomed(like 150% bigger) than the actual size, I want my desginer view to be normal. There is no problems with the form properties or something else. You will see what I mean on the image.
Anyone who knows how to solve this?
Thank you!

A: In my case something strange was with DPI setting in my Windows 10 system.
Solution was change DPI setting (Change the size of text,...) in Display settings, logout / login into system and change DPI setting back. After next login designer zoom was recovered.


text:
Q: DISTINCT ON in an aggregate function in postgres For my problem, we have a schema whereby one photo has many tags and also many comments. So if I have a query where I want all the comments and tags, it will multiply the rows together. So if one photo has 2 tags and 13 comments, I get 26 rows for that one photo:
SELECT
        tag.name,
        comment.comment_id
FROM
        photo
        LEFT OUTER JOIN comment ON comment.photo_id = photo.photo_id
        LEFT OUTER JOIN photo_tag ON photo_tag.photo_id = photo.photo_id
        LEFT OUTER JOIN tag ON photo_tag.tag_id = tag.tag_id

That's fine for most things, but it means that if I GROUP BY and then json_agg(tag.*), I get 13 copies of the first tag, and 13 copies of the second tag.
SELECT json_agg(tag.name) as tags
FROM
        photo
        LEFT OUTER JOIN comment ON comment.photo_id = photo.photo_id
        LEFT OUTER JOIN photo_tag ON photo_tag.photo_id = photo.photo_id
        LEFT OUTER JOIN tag ON photo_tag.tag_id = tag.tag_id
GROUP BY photo.photo_id

Instead I want an array that is only 'suburban' and 'city', like this:
 [
      {"tag_id":1,"name":"suburban"},
      {"tag_id":2,"name":"city"}
 ]

I could json_agg(DISTINCT tag.name), but this will only make an array of tag names, when I want the entire row as json. I would like to json_agg(DISTINCT ON(tag.name) tag.*), but that's not valid SQL apparently.
How then can I simulate DISTINCT ON inside an aggregate function in Postgres?

A: The most simple thing I discovered is to use DISTINCT over jsonb (not json!).
(jsonb_build_object creates jsonb objects)
SELECT
   JSON_AGG(
       DISTINCT jsonb_build_object('tag_id', photo_tag.tag_id,
                                  'name', tag.name)) AS tags
FROM photo
    LEFT OUTER JOIN comment ON comment.photo_id = photo.photo_id
    LEFT OUTER JOIN photo_tag ON photo_tag.photo_id = photo.photo_id
    LEFT OUTER JOIN tag ON photo_tag.tag_id = tag.tag_id
GROUP BY photo.photo_id

A: As stated in comments, json_agg does not serialize a row as an object, but builds a JSON array of the values that you pass it.  You'll need row_to_json to turn your row into a JSON object, and then json_agg to perform the aggregation to an array:
SELECT json_agg(DISTINCT row_to_json(comment)) as tags
FROM
    photo
    LEFT OUTER JOIN comment ON comment.photo_id = photo.photo_id
    LEFT OUTER JOIN photo_tag ON photo_tag.photo_id = photo.photo_id
    LEFT OUTER JOIN tag ON photo_tag.tag_id = tag.tag_id
GROUP BY photo.photo_id

A: Whenever you have a central table and want to left-join it to many rows in table A and also left-join it to many rows in table B, you get these problems of duplicating rows. It can especially throw off aggregrate functions like COUNT and SUM if you're not careful! So I think you need to construct your tags-for-each-photo and comments-for-each-photo separately, and then join them together:
WITH tags AS (
  SELECT  photo.photo_id, json_agg(row_to_json(tag.*)) AS tags
  FROM    photo
  LEFT OUTER JOIN photo_tag on photo_tag.photo_id = photo.photo_id
  LEFT OUTER JOIN tag ON photo_tag.tag_id = tag.tag_id
  GROUP BY photo.photo_id
),
comments AS (
  SELECT  photo.photo_id, json_agg(row_to_json(comment.*)) AS comments
  FROM    photo
  LEFT OUTER JOIN comment ON comment.photo_id = photo.photo_id
  GROUP BY photo.photo_id
)
SELECT  COALESCE(tags.photo_id, comments.photo_id) AS photo_id,
        tags.tags,
        comments.comments
FROM    tags
FULL OUTER JOIN comments
ON      tags.photo_id = comments.photo_id

EDIT: If you really want to join everything together without CTEs, this looks like it gives correct results:
SELECT  photo.photo_id,
        to_json(array_agg(DISTINCT tag.*)) AS tags,
        to_json(array_agg(DISTINCT comment.*)) AS comments
FROM    photo
LEFT OUTER JOIN comment ON comment.photo_id = photo.photo_id
LEFT OUTER JOIN photo_tag on photo_tag.photo_id = photo.photo_id
LEFT OUTER JOIN tag ON photo_tag.tag_id = tag.tag_id
GROUP BY photo.photo_id

A: The cheapest and simplest DISTINCT operation is ... not to multiply rows in a "proxy cross join" in the first place. Aggregate first, then join. See:

*

*Two SQL LEFT JOINS produce incorrect result
Best for returning few selected rows
Assuming you actually don't want to retrieve the whole table, but just one or few selected photos at a time, with aggregated details. Then LATERAL subqueries are fast and elegant:
SELECT *
FROM   photo p
CROSS  JOIN LATERAL (
   SELECT json_agg(c) AS comments
   FROM   comment c
   WHERE  photo_id = p.photo_id
   ) c1
CROSS  JOIN LATERAL (
   SELECT json_agg(t) AS tags
   FROM   photo_tag pt
   JOIN   tag       t USING (tag_id)
   WHERE  pt.photo_id = p.photo_id
   ) t
WHERE  p.photo_id = 2;  -- arbitrary selection

This returns whole rows from comment and tag, aggregated into JSON arrays separately. Rows are not multiplies like in your attempt, but they are only as "distinct" as they are in your base tables.
To additionally fold duplicates in the base data, see below.
Notes:

*

*LATERAL and json_agg() require Postgres 9.3 or later.

*json_agg(c) is short for json_agg(c.*).

*We do not need to LEFT JOIN because an aggregate function like json_agg() always returns a row.
Typically, you'd only want a subset of columns - at least excluding the redundant photo_id:
SELECT *
FROM   photo p
CROSS  JOIN LATERAL (
   SELECT json_agg(json_build_object('comment_id', comment_id
                                   , 'comment', comment)) AS comments
   FROM   comment
   WHERE  photo_id = p.photo_id
   ) c
CROSS  JOIN LATERAL (
   SELECT json_agg(t) AS tags
   FROM   photo_tag pt
   JOIN   tag       t USING (tag_id)
   WHERE  pt.photo_id = p.photo_id
   ) t
WHERE  p.photo_id = 2;

json_build_object() was introduced with Postgres 9.4. Used to be cumbersome in older versions because a ROW constructor doesn't preserve column names. But there are generic workarounds:

*

*Return multiple columns of the same row as JSON array of objects
Also allows to choose JSON key names freely, you don't have to stick to column names.
Best for returning all or most rows
SELECT p.*
     , COALESCE(c1.comments, '[]') AS comments
     , COALESCE(t.tags, '[]') AS tags
FROM   photo p
LEFT   JOIN (
   SELECT photo_id
        , json_agg(json_build_object('comment_id', comment_id
                                   , 'comment', comment)) AS comments
   FROM   comment c
   GROUP  BY 1
   ) c1 USING (photo_id)
LEFT  JOIN LATERAL (
   SELECT photo_id , json_agg(t) AS tags
   FROM   photo_tag pt
   JOIN   tag       t USING (tag_id)
   GROUP  BY 1
   ) t USING (photo_id);

Once we retrieve enough rows, this gets cheaper than LATERAL subqueries. Works for Postgres 9.3+.
Note the USING clause in the join condition. This way we can conveniently use SELECT * in the outer query without getting duplicate columns for photo_id. I didn't use SELECT * here because your deleted answer indicates you want empty JSON arrays instead of NULL for no tags / no comments.
Also remove existing duplicates in base tables
You can't just json_agg(DISTINCT json_build_object(...)) because there is no equality operator for the data type json. See:

*

*How to query a json column for empty objects?
There are various better ways:
SELECT *
FROM   photo p
CROSS  JOIN LATERAL (
   SELECT json_agg(to_json(c1.comment)) AS comments1
        , json_agg(json_build_object('comment', c1.comment)) AS comments2
        , json_agg(to_json(c1)) AS comments3
   FROM  (
      SELECT DISTINCT c.comment  -- folding dupes here
      FROM   comment c
      WHERE  c.photo_id = p.photo_id
   -- ORDER  BY comment --  any particular order?
      ) c1
   ) c2
CROSS  JOIN LATERAL (
   SELECT jsonb_agg(DISTINCT t) AS tags  -- demonstrating jsonb_agg
   FROM   photo_tag pt
   JOIN   tag       t USING (tag_id)
   WHERE  pt.photo_id = p.photo_id
   ) t
WHERE  p.photo_id = 2;

Demonstrating 4 different techniques in comments1, comments2, comments3 (redundantly) and tags.
db<>fiddle here
Old: sqlfiddle backpatched to Postgres 9.3; sqlfiddle for Postgres 9.6


text:
Q: Installation of Ubuntu 14.10 alongside Windows 7 I want to install Ubuntu 14.10 64bit version in my pc alongside Windows 7 64bit OS. So I have installed Windows 7 and now when I tried to install Ubuntu, it doesn't detect any OS and shows it doesn`t have any OS. What to do now?

A:
* First you need to create a new partition from windows for installing ubuntu (around 20 GB) or more if you need

*Then follow these instruction
To install ubuntu alongside windows.


text:
Q: Can I use a combination of SUBSTR() and CHARINDEX() to return a particular line in a body of text? I am writing a T-SQL function that returns an account number from a block of text. The text is generated by the system, and has 3 colons so I need to try to find a way to use SUBSTR() on the row containing "Account:" and not just the colon itself:
Amount: $10.00
Date: 12/5/2022
Account: Mr. John Doe 83850
What would be the cleanest way to select only the line containing the account number to my function for parsing into an integer?

A: I'll probably mess this up on my phone but something like this should help:
SUBSTRING(TEXT,(PATINDEX('%ACCOUNT:%',TEXT)+9),LEN(TEXT)-(PATINDEX('%ACCOUNT:%',TEXT)+9))

Edit:
You could find the third line by finding your 3rd carriage return and line feed using char(10)+char(13), but that could look messy going 3 levels deep so I wont attempt it on my phone


text:
Q: Android app ad-hoc distribution and code signing ( detecting  UID ) Is there a way to code-sign (to allow it to open only on a device with specific ID) your Android app when using ad-hoc distribution (sending app to testers or clients as a subcontractor)?
I know I can share apk file pretty easily, but what if I don't want other people to redistribute the app before it is ready? I don't want testers to be able to distribute not finished and buggy version of my app for example. Or I would like to show my client the final version of the app, but not allow them to distribute it until the payment is made.

A: I did something similar.
Previously i get the IMEI of the tester device
and then on the  onCreate() function
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

String IMEITesterDevice = "1234123535346453634";

 final TelephonyManager  mTelephony =  (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    String AndroidDeviceId = mTelephony.getDeviceId();

if (AndroidDeviceId.contentEquals(IMEITesterDevice ) //Not equal then
 super.finish();  //force to finish my app.
...
...
...
}

UPDATE :
for devices without telephony support like tablets you will get null using TelephonyManager, is better to use  Secure.ANDROID_ID for some devices...
String AndroidDeviceId;
final TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);//for mobiles
    if (mTelephony.getDeviceId() != null)
        AndroidDeviceId = mTelephony.getDeviceId();
    else // Tablets
        AndroidDeviceId = Secure.getString(
                        getApplicationContext().getContentResolver(),
                        Secure.ANDROID_ID);


text:
Q: Unable to send mail when trying to get mail recipient from a file outside the script in the same dir I use the code below and it's working fine.
dl=xyz@somebody.com

mail -t $dl << EOM
  Subject: Report Status $(date)
  Content-Type: text/html
  mail text
EOM

However, when I try to get the mail id from file dl.txt, no mail is sent.
dl='/script/user/dl.txt'

mail -t $(echo cat $dl) << EOM
  subject: Report Status $(date)
  content-Type: text/html
  mail text
EOM

Note: text file contains mail ids.

A: If you try to run
dl='/script/user/dl.txt'
echo cat $dl

The output will be
cat /script/user/dl.txt

Remove echo or better change code like this
to=$(cat '/script/user/dl.txt')

mail -t $to << EOM
  Subject: Report Status $(date)
  Content-Type: text/html
  mail text
EOM